Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript add class depending on current URL

For my website navigation I need to add the class 'active' to the li element depending on if 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>
like image 343
Kristian Matthews Avatar asked Dec 28 '22 11:12

Kristian Matthews


2 Answers

If you want to use "pure" ("vanilla") JavaScript, use the following code(assuming that <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");
        }
    });
});
like image 165
Rob W Avatar answered Jan 05 '23 10:01

Rob W


I think, in this case, is better change in server side.

Using javascript you can do:

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 loaded 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 the way to know if the document is loaded.

like image 40
Ratata Tata Avatar answered Jan 05 '23 10:01

Ratata Tata