Goran Stošić
Goran Stošić

Reputation: 95

adding .active class on a <button> that shows corresponding <div>

I am working on a menu that opens/hides divs inside a single page.

What I'm trying to do is apply a class (.active) on a currently clicked menu item as long as div connected to it is opened. As soon as div is closed, or other menu item is selected, class would dissapear / be applied to other menu item.

I tried to go with $(".your_selector li").addClass("active"); but it does nothing but marks all menu items as active, as you would expect.

How would you tackle that problem? Here is the fiddle http://jsfiddle.net/4DGUV/3/

Thanks in advance

Upvotes: 1

Views: 7684

Answers (3)

Jai
Jai

Reputation: 74738

Change to this script: http://jsfiddle.net/4DGUV/7/

$('document').ready(function () {
  $('button').click(function () {      //<----click the buttons
      $('button').removeClass('active'); //<-----remove the class from the button
      $(this).addClass('active'); //<---add the class to currently clicked button
      var $div = $('#' + $(this).data('href'));
      $('.demo').not($div).hide();
      $div.slideToggle();
   });
});

or a better way: http://jsfiddle.net/4DGUV/8/

$('document').ready(function () {
  $('.menu li').click(function () {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    var $div = $('#' + $(this).data('href'));
    $('.demo').not($div).hide();
    $div.slideToggle();
  });
});

then you html should be like this:

<div class="menu">
  <ul>
    <li> <a href='#' id="show2" data-href="vission1">news</a>

    </li>
    <li> <a href='#' id="show3" data-href="mteam">team</a>

    </li>
    <li> <a href='#' id="show1" data-href="mission1">download</a>

    </li>
  </ul>
</div>

Upvotes: 4

Raed Alsaleh
Raed Alsaleh

Reputation: 1621

use the following :

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

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

You need to add it inside click event of li.

Example

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

Because what you are trying is addClass to all the li tag so you need to tell jquery to addClass to specific li which are clicked.

Upvotes: 0

Related Questions