barteloma
barteloma

Reputation: 6875

jquery selected link activate but different div

I want to activate selected link with jquery. But my links are grouped with css classes in different divs.

<div class="menu-container">
    <div class="button-group">
        <a href="#" id="manu1">clients</a>
        <a href="#" id="menu2">supplier</a>
    </div>
    <div class="button-group">
        <a href="#" id="menu3">supplier</a>
    </div>
</div>

Jquery is like this.

$('div.menu-container').on('click','.button-group > a', function(){
      $(this).addClass('active').siblings('a').removeClass('active');
})

I want to change selected link to active css class and others not. But my button-group is separating a tags. So two a link is appearing as active.

working app jsfiddle is here.

Upvotes: 0

Views: 188

Answers (5)

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13998

You are removing the active class only for siblings element. Simply remove the active class for all anchor element like below. Update your script like below.

 $('div.menu-container').on('click','.button-group > a', function(){
 $('.button-group > a').removeClass('active');
 $(this).addClass('active');
 })

DEMO

EDIT:

According to your new requirement if I click the second time to active link, it should be deactive, update your jquery like below.

  $('div.menu-container').on('click','.button-group > a', function(){
    if($(this).hasClass('active'))
    {
       $(this).removeClass('active'); 
    }
    else
    {
       $('.button-group > a').removeClass('active'); 
       $(this).addClass('active'); 
    }
 });

DEMO

Upvotes: 1

Naresh Pansuriya
Naresh Pansuriya

Reputation: 2045

please see solution,

$('div.menu-container').on('click','.button-group > a', function(){
    $('div.menu-container').find('a.active').removeClass('active');
    $(this).addClass('active');
})

Upvotes: 1

chandu
chandu

Reputation: 2276

Try like this:::

$(document).ready(function(){
    $("a[id ^= 'menu']").on('click',function(){
        $("a[id ^= 'menu']").removeClass('active');
        $(this).addClass('active')
    })


})

DEMO

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : remove active class from all anchor links present under .menu-container and then apply 'active' class to current clicked element.

$('div.menu-container').on('click','.button-group > a', function(){
      $('div.menu-container').find('.active').removeClass('active');
      $(this).addClass('active');

});

Demo

Upvotes: 1

red-X
red-X

Reputation: 5138

you need to go further upwards to reach them, try this:

$('div.menu-container').on('click','.button-group > a', function(){
  $(this).closest('.menu-container').find('a.active').removeClass('active');
  $(this).addClass('active');
});

Upvotes: 1

Related Questions