PrivateUser
PrivateUser

Reputation: 4524

add active class in menu li using jquery

As of now i'm using code like this

<script>
jQuery(document).ready(function($) {
  $("#menu li").click(function(){ 
      if ($("#menu li").hasClass('active')) {
        $("#menu li").removeClass('active'); 
      }
    $(this).addClass('active');
 });
});
</script> 

Its working only for tabbed navigation.

But my site uses different pages. I mean each href points to different pages.

Can someone tell me how to add active class to li either using jquery or css.?

Thanks

Upvotes: 2

Views: 8420

Answers (2)

Hardik
Hardik

Reputation: 1283

Try following.

$('li').each(function(){
    if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
    {
    $(this).addClass('active').siblings().removeClass('active');
    }
});

Upvotes: 5

David Ziemann
David Ziemann

Reputation: 970

You can add an active class to a page and run it in a similar way. When the page loads (document.ready()), tell it to attach the active class to the current page menu list item.

$(/*Your current page menu item*/).addClass('active');

Upvotes: 1

Related Questions