Reputation: 6875
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
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');
})
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');
}
});
Upvotes: 1
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
Reputation: 2276
Try like this:::
$(document).ready(function(){
$("a[id ^= 'menu']").on('click',function(){
$("a[id ^= 'menu']").removeClass('active');
$(this).addClass('active')
})
})
Upvotes: 1
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');
});
Upvotes: 1
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