Jquery Make Navigation Active

Add Active Class to Navigation / Menu using Jquery

September 16, 2020

Sample HTML Navigation

<ul class="navbar">
    <li><a href="/">Home</a>
    <li><a href="/home/about">About</a>
    <li><a href="/home/contact#call">Contact</a>
    <li><a href="/blogs">Blogs</a>
    <li><a href="/blogs/search?q=1">Search</a>
</ul>

Jquery Code to Make Navigation Active On Page Load

$(function () {
 
    var curURL = window.location.pathname;
 
    $("ul.navbar li a").each(function () {
 
        var navHref = $(this)[0].pathname;
 
        if (curURL.toLowerCase() === navHref.toLowerCase()) {
            $(this).addClass("active");  // TO SET ACTIVE CLASS ON ANCHOR
            $(this).closest("li").addClass("active");  // TO SET ACTIVE CLASS ON PARENT <li>
        }
    });
});

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...