JavaScript

Add .active class to current menu based on URL

How to get the URL of the current page using and adding an active class to navigation based on URL. With the jQuery find the best way to the highlight the active section in the navigation menu.

Add active class to menu
Add .active class to current navigation based on URL

The following example will show you how to find the current page URL using jQuery.:-

<script>
  jQuery(function($) {
      var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
        $(".navbar-nav > li > a").each(function(){
        if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
        $(this).addClass("active");
        // $(this).parent("li").addClass("active");
      })
  });
</script>

Add active class to menu

Based on navigation structure you can write the jQuery, here .active class add to .navbar-nav > li > a, so depends on menu write code.

You can customize this code further as per your requirement.

Add .active class to current menu based on URL