Question

Well, I can add the selected class to my parent li item in menu by using

$(function(){
   var path = location.pathname.substring(1);
   if ( path )
     $('#main-menu a[href$="' + path + '"]').parent('li').addClass('selected');
});

But it doesn't work for my home page with href="/". How can I change this function to add selected class to home page when it's active as well? Thanks.

Était-ce utile?

La solution

EDIT based on the new information about your URL formats, I would go for this:

$(function() {
    $('#main-menu a').filter(function() {
        return this.href === location.href;
    }).parent('li').addClass('selected');
});

Using the .filter function and comparing the .href property does the check on the full URL, rather than on the relative URLs that can appear within the href attribute.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top