jquerynavigationaddclasscurrent-page

Highlight current page navigation link


I've hardcoded a subnavigation and would like to highlight the navbar item of the current page by simply adding a class 'active' to those links. But the following HTML-Markup in combination with the javascript adds the active class to every li(.irp-menu-item) and not just to the closest li. It would be necessary that the script only adds the class to the closest li and not to the other ones aswell, but somehow I am not able to solve this issue.

HTML-Markup:

<nav id="irp-subnav" class="css-sticky" role="navigation" aria-label="irp-subnav" lang="de-DE">
   <div class="irp-wrapper">
        <div class="irp-background"></div>
        <div class="irp-content">
            <span class="irp-title">
                  TITLE</span>
            <div class="irp-menu">
            <div class="irp-menu-tray">
                <ul class="irp-menu-items">
                  <li class="irp-menu-item"><a href="/LINK-1/" class="irp-menu-link">LINK 1</a>
                                                    </li>
                  <li class="irp-menu-item"><a href="/LINK2/" class="irp-menu-link">LINK 2</a>
                                                    </li>
                  <li class="irp-menu-item"><a href="/LINK3/" class="irp-menu-link">LINK3</a>
                </ul>
            </div>
            <div class="irp-actions irp-actions-right">
                <div class="irp-action irp-action-menucta" aria-hidden="true">

                    <label for="irp-menustate" class="irp-menucta"> <span class="irp-menucta-chevron"></span>
                            </label>
                </div>
            </div>
        </div>
        </div>
    </div>
</nav>

Javascript:

jQuery(document).ready(function($) {
$(function () {
var url = window.location.pathname; 
var activePage = url.substring(url.lastIndexOf('/') + 1); 
    $('.irp-menu-item .irp-menu-link').each(function () { 
        var linkPage = this.href.substring(this.href.lastIndexOf('/') + 1); 

        if (activePage == linkPage) { 
            $(this).closest("li").addClass("active"); 
        }
    });
})
});

Solution

  • I've editited Rami's answer to use the whole href.

    //this makes the current link containing li of class "active"
    $(document).ready(function ($) {
        var url = window.location.href;
        var activePage = url;
        $('.irp-menu-item a').each(function () {
            var linkPage = this.href;
    
            if (activePage == linkPage) {
                $(this).closest("li").addClass("active");
            }
        });
    });