Javascript for nav highlight not working in IE

I have a great little script for highlighting links on a one page site that I found here on Stack Overflow. It works perfectly in Chrome and Edge but not in IE. Here is a snippet. Any suggestions?

<header>
<nav>
<a href="#one">ONE</a>
<a href="#two">TWO</a>
<a href="#three">THREE</a>
<a href="#four">FOUR</a>
<a href="#five">FIVE</a>
</nav>
</header>
<main>
<section id="one">
<section id="two">
<section id="three">
<section id="four">
<section id="five">
</main>

<script>
const links = document.querySelectorAll('nav a');
const sections = document.querySelectorAll('section');

function changeLinkState() {
  let index = sections.length;

  while(--index && window.scrollY + 1 < sections[index].offsetTop) {}

  links.forEach((link) => link.classList.remove('active'));
  links[index].classList.add('active');
}

changeLinkState();
window.addEventListener('scroll', changeLinkState);
</script>

1 thought on “Javascript for nav highlight not working in IE”

  1. I assume that you are using an IE 11 browser.

    The IE browser does not support the Arrow functions(=>). It can be a possible reason that why your code is not working in the IE browser.

    I have tried to modify your code, you can try to make a test with this code and let us know whether it works or not.

    <header>
       <nav>
          <a href="#one">ONE</a>
          <a href="#two">TWO</a>
          <a href="#three">THREE</a>
          <a href="#four">FOUR</a>
          <a href="#five">FIVE</a>
       </nav>
    </header>
    <main>
       <section id="one">
       <section id="two">
       <section id="three">
       <section id="four">
       <section id="five">
    </main>
    <script>
       if (typeof Array.prototype.forEach != 'function') {
        
         Array.prototype.forEach = function (callback) {
           for (var i = 0; i < this.length; i++) {
        
             callback.apply(this, [this[i], i, this]);
           }
         };
       }
        
       if (window.NodeList && !NodeList.prototype.forEach) {
         NodeList.prototype.forEach = Array.prototype.forEach;
        
       }
       
       
       const links = document.querySelectorAll('nav a');
       const sections = document.querySelectorAll('section');
       
       function changeLinkState() {
       
         let index = sections.length;
       
         while(--index && window.scrollY + 1 < sections[index].offsetTop) {}
       
         //links.forEach((link) => link.classList.remove('active'));
        links.forEach(function (link) 
        {
              return link.classList.remove('active');
        });
         links[index].classList.add('active');
       
       }
       
       changeLinkState();
       window.addEventListener('scroll', changeLinkState);
    </script>
    
    Reply

Leave a Comment