JS - Add active class on navigation cross pages

0 votes
265 views
added May 8, 2019 in Javascript by LC Marshal Captain (25,790 points)
window.onload = function() {
    var url = window.location.pathname; 
    var activePage = url.substring(url.lastIndexOf('/') + 1);
    var element = document.getElementById(activePage);
    element.classList.add("active");
};

 

1 Response

0 votes
responded May 8, 2019 by LC Marshal Captain (25,790 points)

classList definition (from w3schools

  • The classList property returns the class name(s) of an element, as a DOMTokenList object.
  • This property is useful to add, remove and toggle CSS classes on an element.
  • The classList property is read-only, however, you can modify it by using the add() and remove() methods.
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...