JavaScript add class based on current url

For my navigation around the site, I need to add the 'active' class to the li element, depending on whether it matches the current URL.

Nav HTML:

<ul id="nav"> <div id="wrapper"> <li><a href="/">Home</a></li> <li><a href="/tagged/Review">Reviews</a></li> <li><a href="/tagged/First_Look">First Looks</a></li> <li><a href="/tagged/Commentary">Commentaries</a></li> <li><a href="/tagged/Walkthrough">Walkthroughs</a></li> <li><a href="/tagged/Achievement">Achievements</a></li> </div> </ul> 
+4
source share
2 answers

If you want to use "vanilla" JavaScript, use the following code (assuming <ul id="nav"> exists):

 window.onload = function() { var all_links = document.getElementById("nav").getElementsByTagName("a"), i=0, len=all_links.length, full_path = location.href.split('#')[0]; //Ignore hashes? // Loop through each link. for(; i<len; i++) { if(all_links[i].href.split("#")[0] == full_path) { all_links[i].className += " active"; } } } 

Using jQuery:

 $(document).ready(function(){ var full_path = location.href.split("#")[0]; $("#nav a").each(function(){ var $this = $(this); if($this.prop("href").split("#")[0] == full_path) { $this.addClass("active"); } }); }); 
+6
source

I think in this case it is better to change the server side.

Using javascript, you can:

 var target = 0; switch( window.location.pathname ) { case "/tagged/Review": target = 1; break; case "/tagged/First_Look": target = 2; break; /* add other cases */ } document.getElementById("nav").getElementByTagName("li")[target].classList.add("active"); 

Put the code after loading the DOM.

If jquery, you can use:

 var target = 0; switch( window.location.pathname ) { case "/tagged/Review": target = 1; break; case "/tagged/First_Look": target = 2; break; /* add other cases */ } $($("#nav li")[target]).addClass("active"); 

EDIT

window.onload or $ .ready is a way to find out if a document is loaded.

0
source

Source: https://habr.com/ru/post/1381932/


All Articles