Reputation: 2126
Being jQuery noob I have a problem and I don't know how to solve it:( I have ul tag and couple li tags inside it. And I am trying to accomplish this : on first click of a button select first li tag, on second click select second li tag and so on... You can see that this is not working as expected (it selects first and second tag). Can someone help me or point me in the right direction? Here's jsFiddle link:http://jsfiddle.net/aH8w2/ Thank you!!!
<script type="text/javascript">
function addCss(){
$('ul li.first').addClass('red');
}
$(document).ready(function(){
$("button").click(function(){
addCss();
});
$("button").click(function(){
if($('ul li.first').is('.red'))
$('ul li.first').next('li').addClass('red');
});
});
</script>
Upvotes: 1
Views: 3459
Reputation: 816422
Another way, which jumps to the beginning of the list again, when the end is reached:
var $lis = $('ul > li');
$("button").click(function(){
var $selected = $('.red').removeClass('red');
($selected.next().length > 0 ? $selected.next() : $lis.first()).addClass('red');
});
Or a bit shorter:
($selected.next().get(0) || $lis[0]).className += 'red';
Upvotes: 2
Reputation: 1354
Try this:
$(document).ready(function(){
$("button").click(function(){
if($('.red').length == 0 || $('.red').next().length == 0){
$('.red').removeClass('red');
$('.first').addClass('red');
}else{
$('.red').removeClass('red').next().addClass('red');
}
});
});
This takes care of the the first click as well as all subsequent clicks. Even going back to the first if you reach the end.
Upvotes: 0
Reputation: 15028
$("button").click(function(){
if($('.red').length > 0) {
$('.red').removeClass('red').next().addClass('red');
} else {
$('li:first').addClass('red');
}
});
You also don't need the .first
on your first li
. jQuery can do li:first
which will select the first matching item.
Upvotes: 2
Reputation: 2663
Try this:
$("button").click(function(){
var current = $('ul li.red');
current.first().next('li').addClass('red');
current.removeClass('red');
});
This assumes that you have at-least one li
that is 'red'.
Upvotes: 0
Reputation: 230336
Try this:
$("button").click(function(){
$('.red').removeClass('red').next('li').addClass('red');
});
Upvotes: 2