skip to Main Content

I’m building a custom menu for my website. What I want to do here is add an active class to highlight the menu item when it matches the current page link.

Example: if the user is on the page https://mywebsite.it/explore-docs then .link_expdocs gains the active class.

I managed to do this with some Javascript, but I don’t like what came out. I’ve iterated the code many times and I don’t think it’s a good practice.

Is there a better and shorter practice so that I don’t repeat the same code every time and so that I don’t have to explicitly write all the classes and slugs in indexOf ?

Sorry, but I’m new and managed to do this by looking around on stackoverflow.

code that I tried to shorten (not work):

I tried to shorten the code like this, but the active class is always added to .link_home even when I’m on other pages, and the same happens with link_dashboard when the /account slug is present in the url

document.addEventListener("DOMContentLoaded", function() {
  const links = document.querySelectorAll(".item_menu a");

  links.forEach(link => {
    if (window.location.href.indexOf(link.getAttribute("href")) > -1) {
      link.classList.add('active');
    }
  });
});

Original code (work):

<!-- Vertical Navigation -->
<div class="vertical_nav">

  <!-- User Menu -->
  <div class="user_menu">
    <div class="wrap_user_navigation">
      <div class="user_navigation">
        <div class="item_menu">
          <a class="link_dashboard" href="https://mywebsite.it/account">Dashboard</a>
        </div>

        <div class="item_menu">
          <a class="link_ordini" href="https://mywebsite.it/orders">I miei ordini</a>
        </div>

        <div class="item_menu">
          <a class="link_downloads" href="https://mywebsite.it/downloads">Libreria Downloads</a>
        </div>

        <div class="item_menu">
          <a class="link_settings" href="https://mywebsite.it/settings">Impostazioni</a>
        </div>
      </div>  
    </div>  
  </div>

  <div class="main_menu">
    <div class="item_menu">
      <a class="link_home" href="https://mywebsite.it/">Home</a>
    </div>  

    <div class="item_menu">
      <a class="link_expdocs" href="https://mywebsite.it/explore-docs">Explore Docs</a>
    </div> 

    <div class="item_menu">
      <a class="link_coaching" href="https://mywebsite.it/services">Online Coaching</a>
    </div> 

    <div class="item_menu">
      <a class="link_calculator" href="https://mywebsite.it/math">Fitness Calculator</a>
    </div> 
  </div>

  <!-- Docs Menu -->
  <div class="doc_menu">
    <div class="item_menu">
      <a class="link_anadocs" href="https://mywebsite.it/docs-anatomy">Docs Anatomy</a>
    </div> 

    <div class="item_menu">
      <a class="link_evidence" href="https://mywebsite.it/evidence-based">Evidence Based</a>
    </div> 

    <div class="item_menu">
      <a class="link_strengthvalue" href="https://mywebsite.it/strength-value">Strength Value</a>
    </div> 

    <div class="item_menu">
      <a class="link_mission" href="https://mywebsite.it/mission">Mission</a>
    </div> 
  </div>

  <!-- Footer Items -->
  <div class="footer_menu">
    <div class="item_menu">
      <a class="link_support" href="https://mywebsite.it/supporto">Supporto</a>
    </div> 

    <div class="item_menu">
      <a class="link_logout" href="https://mywebsite.it/wp-login.php?action=logout">Logout</a>
    </div> 
  </div>

</div>
document.addEventListener("DOMContentLoaded", function() {

  // Add - Remove class active for user_menu
  if(window.location.href.indexOf("account") > -1) {
    document.querySelector(".link_dashboard").classList.add('active');
  } 
  if(window.location.href.indexOf("orders") > -1) {
    document.querySelector(".link_ordini").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  }   
  if(window.location.href.indexOf("downloads") > -1) {
    document.querySelector(".link_downloads").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  } 
  if(window.location.href.indexOf("settings") > -1) {
    document.querySelector(".link_settings").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  } 

  // Add - Remove class active for main_menu
  if(window.location.href === "https://mywebsite.it/") {
    document.querySelector(".link_home").classList.add('active');
  }
  if(window.location.href.indexOf("explore-docs") > -1) {
    document.querySelector(".link_expdocs").classList.add('active');
  }   
  if(window.location.href.indexOf("services") > -1) {
    document.querySelector(".link_coaching").classList.add('active');
  } 
  if(window.location.href.indexOf("math") > -1) {
    document.querySelector(".link_calculator").classList.add('active');
  }

  // Add - Remove class active for doc_menu
  if(window.location.href.indexOf("docs-anatomy") > -1) {
    document.querySelector(".link_anadocs").classList.add('active');
  } 
  if(window.location.href.indexOf("evidence-based") > -1) {
    document.querySelector(".link_evidence").classList.add('active');
  }   
  if(window.location.href.indexOf("strength-value") > -1) {
    document.querySelector(".link_strengthvalue").classList.add('active');
  } 
  if(window.location.href.indexOf("mission") > -1) {
    document.querySelector(".link_mission").classList.add('active');
  }
});

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @CodeThing answer I came to this solution which is working for me.

    // Get url current page
    var currentUrl = window.location.href;
    
    // Remove slash ("/") from the current page's URL
    if (currentUrl.slice(-1) === "/") {
      currentUrl = currentUrl.slice(0, -1);
    }
    
    // Select all <a> tags in the vertical menu
    var menuLinks = document.querySelectorAll('.vertical_nav a');
    
    // Iterate through all the links in the menu and add class "active" if the URL of the link matches the URL of the current page
    menuLinks.forEach(function(link) {
      var linkUrl = link.href;
    
      // Remove slash ("/") from the current page's URL
      if (linkUrl.slice(-1) === "/") {
        linkUrl = linkUrl.slice(0, -1);
      }
    
      if (linkUrl === currentUrl) {
        link.classList.add('active');
      }
    });
    

  2. You need to get exact part of url to compare. For this we can split the href with / so this will create array, reverse that array and take the first element.

    document.addEventListener("DOMContentLoaded", function() {
      const links = document.querySelectorAll(".item_menu a");
    
      links.forEach(link => {
        /*let slug = link.getAttribute("href").split("/").reverse()[0];
        if (window.location.href.indexOf(slug) > -1) {
          link.classList.add('active');
        }*/
    
        if (window.location.href === link.getAttribute("href")) {
          link.classList.add('active');
        }
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search