Reputation: 2952
I've the following html code
<ul class='selectul'>
<li class='active'><a href='?sortby=views'>by Popularity.</a></li>
<li><a href='?sortby=recency'>by Recency.</a></li>
<li><a href='?sortby=alphabet'>Alphabetically.</a></li>
</ul>
When any <li>
element is clicked, I want to add class='active'
to it. None of its siblings is then allowed to have this class. I tried to do this with the following jQuery code
(function(){
$('.selectul li').on('click',function(){
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
}())
but it doesn't seem to do anything. I'm just getting started with jQuery so I apologize if this question is rather basic.
Upvotes: 1
Views: 1651
Reputation: 314
The script is all right. The problem is somewhere else. Once you click the link, the document reload and you do not notice the change of classes.
Try:
(function(){
$('.selectul li').on('click',function(){
$(this).addClass('active');
$(this).siblings().removeClass('active');
return false;
});
}());
return false interrupts the Click-Event and prevent the reload of the document.
Upvotes: 5
Reputation: 17366
I think you should code like this
$(document).ready(function(){
$('.selectul li').on('click',function(){
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
});
Upvotes: 0
Reputation: 4778
Your code looks good, and I have verified it working @ jsfiddle.net
$(document).ready(function(){
$('.selectul li').on('click',function(){
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
});
Upvotes: 1
Reputation: 765
Try waiting for a document ready event as the elements might not be on the page yet.
$(function(){
$('.selectul li').on('click',function(){
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
});
Upvotes: 0