I'm working on a little problem. I have <li> elements and I want to change their
background color on each click. In my code, I am trying to count the clicks.
If the click = 1, then the background color would be red. If the click = 2, then the background color would be blue. If the click = 3, the background color would revert to the original and the count will be back to 0;
6 Answers
Is this what you need?
$(function() {
$("#sortable li").each(function() {
var count = 0;
$(this).click(function(){
count++;
if (count === 1) {
$(this).addClass('on');
}
else if(count === 2){
$(this).removeClass('on');
$(this).addClass('absent');
}
else{
$(this).removeClass('absent');
count = 0;
}
});
});
});
3 Comments
count++;, so there is no need to use too much ++.you can use the .data() to keep track on the specific lis 'state' (or you just if it has a specific cssClass and not use a counter, but if you want to keep the counter: http://jsfiddle.net/j8s3D/13/
Comments
var arry = ['red', 'blue','orange'], i=0, len= arry.length;
$('#element').on('click',function(){
$(this).css('background',arry[i++]);
if(i===len){i=0;}
});
Comments
You increment count too much!
Note that you can cache the $(this) object rather than construct new jQuery object on every line!
Fixed code:
$(function() {
$("#sortable li").click(function() {
var $this = $(this);
var count = $this.data('count') || 1;
if (count === 1) {
$this.addClass('on');
}
else if (count === 2) {
$this.removeClass('on').addClass('absent');
}
else {
$this.removeClass('absent');
count = 1;
}
$this.data('count', count+1);
});
});
2 Comments
$this.removeClass('on').addClass('absent');You can use .data() to associate the number with the element. You should also cache $(this) and maybe use a switch instead of an if/else structure. Finally, you can chain the removeClassand adddClass methods. http://jsfiddle.net/pXFs6/
$(function() {
$("#sortable li").click(function() {
$ele = $(this);
count = $ele.data().count || 1;
switch(count) {
case 1:
$ele.addClass('on');
break;
case 2:
$ele.removeClass('on')
.addClass('absent');
break;
default:
$ele.removeClass('absent');
count = 0;
break;
}
$ele.data('count', count+1);
});
});
Comments
I would like to offer you another variant (a little bit optimized):
$(function() {
$("#sortable li").each(function() {
var count = 0;
$(this).click(function(){
var $this = $(this);
count++;
if (count === 1) {
$this.addClass('on');
}
else if(count === 2){
$this.addClass('absent');
}
else{
$this.removeAttr('class');
count = 0;
}
});
}); });