Skip to content Skip to sidebar Skip to footer

Keep Menu Item Active After Clicking On Link On Current Page

Basically, I'm trying to add the class active to the current menu item. I succeeded by using the following jQuery code. jQuery(document).ready(function($){ var path = w

Solution 1:

Try changing

var path = window.location.href;

to this:

var path = "/" + window.location.pathname.split('/')[1];

pathname retrieves everything after (and including) the first slash. split will break the string into a list of strings based on a defined separator ('/'), and we are going to choose the item with an index of 1.

Solution 2:

Try this one. Worked for me. Found it somewhere on the net, but don't remember the source.

var i = document.location.href.lastIndexOf("/");
var current = document.location.href.substr(i+1);

    $("#nav-main a").removeClass('active');

    $("#nav-main a[href^='"+current+"']").each(function(){
        $(this).addClass('active');
    });

Post a Comment for "Keep Menu Item Active After Clicking On Link On Current Page"