[SOLVED] Adding an active class to the navbar

Issue

This is how my code looks like:

<div class="header-nav navbar-collapse collapse ">
      <ul id="navigation" class=" nav navbar-nav">       
                   <li>
                        <a href="index.html">Home</a>
                                
                   </li>
                            
                    <li>
                        <a href="about-us.html">About Us</a>
                    </li>
                     
                    </ul>
                    </div>

I’ve been trying to add the active class to each of them when the user is on that specific page but no succes so far
Tis is how my script looks like:

     var i = 0;
  [].forEach.call(document.querySelectorAll('li > a'), function(nav) {
    console.log(nav.pathname,window.location.pathname);
    if (nav.pathname === window.location.pathname){
        i = 1;
        console.log(i);
      nav.classList.add('active')
    }
        
    else{
         console.log(i)
         nav.classList.removeClass('active')
  }
    

  })           

The active class is set on the "a" not on "li" and i don’t know how to fix this. Maybe someone can help me?

Solution

In looking at the classes, it looks like you may be using Bootstrap. I added in those libs to the snippet, and updated some of the classes. I also added in another nav item with the href equal to js since that is the pathname for the snippet window. Otherwise it won’t add the active class as there would not be a pathname that would be equal.

I also changed the nav items to pills, so you can see the active link easier.

var i = 0;
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
    console.log({
      navPathname: nav.pathname,
      windowLocationPathname: window.location.pathname,
      areEqual: nav.pathname === window.location.pathname,
    });
  if (nav.pathname === window.location.pathname) {
    nav.classList.add('active')
  } else {
    nav.classList.remove('active')
  }
})
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<div class="navbar navbar-light bg-light">
  <ul id="navigation" class="nav nav-pills">
    <li class="nav-item">
      <a class="nav-link" href="index.html">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="js">JS</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="about-us.html">About Us</a>
    </li>
  </ul>
</div>

Answered By – Steve

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *