Skip to content Skip to sidebar Skip to footer

Jquery Keep Active Menu Item Highlighted

I have a menu: http://jsfiddle.net/hu5x3hL1/3/ HTML

Solution 1:

You will have to do the check in the dom ready handler, not in the click handler

$('#menu1 li a').click(function (e) {
    $('a').removeClass('dropdown-class-name active');
    $(this).addClass('dropdown-class-name active');
});

var url = window.location.pathname;//need to make sure that this is the href value
$('#menu1 li a[href="'+url+'"]').addClass('dropdown-class-name active');

Solution 2:

Try this

$('#menu1 li a').click(function(e) {
    if($('a').hasClass('dropdown-class-name active')=="false"){$('a').removeClass('dropdown-class-name active');}
    $(this).addClass('dropdown-class-name active');
});

http://jsfiddle.net/hu5x3hL1/4/

Solution 3:

the below code should work

$("#menu1 li a").click(function() {
    var$Link = $(this); // cache it as we will use ot mote than once//also url == a.href cannot return true if you use relative url in the link.//url most likely http://domain.com/pagename href will be just a page name//if active do nothingif (!$Link.hasClass("active")) {
        $Link.closest("ul") //find menu container
            .find("a.active").removeClass('active'); //find active and remove it$Link.addClass('active');
    }
});

Solution 4:

did you tried to put the anchor reference in the selector?

var localURL = '[href="'+window.location.href+'"]'

$('#menu1 li a'+localURL).click(function(e) {
    $('a').removeClass('dropdown-class-name active');
    $(this).addClass('dropdown-class-name active');
});

http://jsfiddle.net/hnxhcbgw/1/

keep in mind that this will only run on click events, you should do it too on load event.

Post a Comment for "Jquery Keep Active Menu Item Highlighted"