william
william

Reputation: 217

change active li when clicking a link jquery

I want to make a menu, and change the class when clicking.

When i click on the "li" with no class="active", i want jquery to add a class on the empty <li> and remove it from the othes "li".

<li class="active"><a href="javascript:;" onclick="$.data.load(1);">data</a></li>
<li><a href="javascript:;" onclick="$.data.load(2);">data 2</a></li>

can somebody help me ? :)

Upvotes: 14

Views: 93179

Answers (5)

Shobi
Shobi

Reputation: 11461

$(window).load(function(){
    page=window.location.pathname.split("/").pop();
    menuChildren = $('a[href="' + page + '"]');  
    $(menuChildren).parent('li').addClass('active');
});

The above code will look up the url and pop out the last element (Which is the file name). Then it finds the anchor tag with href attribute which has the same value of the url then it puts an active class for its parent li tag

Upvotes: 3

Greg
Greg

Reputation: 321618

$('li').click(function()
{
    $('li', $(this).parent()).removeClass('active');
    $(this).addClass('active');
}

Upvotes: 4

karim79
karim79

Reputation: 342635

I think you mean this:

$('li > a').click(function() {
    $('li').removeClass();
    $(this).parent().addClass('active');
});

Upvotes: 26

Andy Gaskell
Andy Gaskell

Reputation: 31761

This should get you close.

$("li").click(function() {
  $("li").removeClass("active");
  $(this).addClass("active");
});

Upvotes: 1

Sampson
Sampson

Reputation: 268344

// When we click on the LI
$("li").click(function(){
  // If this isn't already active
  if (!$(this).hasClass("active")) {
    // Remove the class from anything that is active
    $("li.active").removeClass("active");
    // And make this active
    $(this).addClass("active");
  }
});

Upvotes: 15

Related Questions