Highlight current page navigation link

user5991491 picture user5991491 · Jun 2, 2016 · Viewed 10.2k times · Source

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"); 
        }
    });
})
});

Answer

Rupesh Wankhede picture Rupesh Wankhede · Mar 13, 2018

Use the Javascript code and style given below and include In your Header:

<style>
    a.current {
        color: orange !important;
    }
</style>
<script>
    $(function () {
        $('.irp-menu li a').each(function () {
            if ($(this).prop('href') == window.location.href) {
                $(this).addClass('current');
            }
        });
    });
</script>