Reputation: 9247
I'm trying to set active link when user clik on it but i cant figureout how to remove last clicked. This is my fiddle:
http://jsfiddle.net/9ff79/222/
$(function() {
$( 'nav ul li a' ).on( 'click', function() {
$(this).parent().find( 'nav ul li a .active' ).removeClass('active');
$(this).addClass('active');
});
});
Upvotes: 2
Views: 2204
Reputation: 1720
Unless you have more nav-elements you a and .active. That is implying you have a child element with the class active.
Try this:
$( 'nav ul li a.active' ).removeClass('active');
Upvotes: 0
Reputation: 3265
This is how I got there:
$(function() {
$('nav ul li a').on('click', function() {
$('nav ul li a').removeClass('active'); // remove active class from ALL href's
$(this).addClass('active'); // add active class for the element clicked
});
});
http://jsfiddle.net/lharby/9ff79/223/
Upvotes: 2
Reputation: 337560
Your DOM traversal from the clicked a
element isn't correct. Use closest()
then find()
to get the current .active
element:
$('nav ul li a').on('click', function () {
$(this).closest('nav ul').find('a.active').removeClass('active');
$(this).addClass('active');
});
Upvotes: 1