Reputation: 40737
I have a 3 div's, the jQuery script adds a class when a div is clicked:
.red{ background-color: red; }
What I would like to do is to modify the jQuery so that once time the .red
class is added an the next time it will add .blue
, .red
, .blue
and so on...
My script ans you can the in this demo is this:
var $a = $('.box');
$a.click(function(){
$(this).addClass('red');
});
I'm sorry I'm not sharing more, but my horrid attempts wil just confuse.
I hope I have made myself clear, if not please ask!!
Thanks in advance!!
UPDATE:
I think the question was not clear enough so I'll try to explain further.
What a need bascially would be three div, the first click, turns the clicked div into red, the second turns the clicked into blue, and the red an so on, they should toggle (go turn red or blue when clicked agin the first click is the only one that counts)
Upvotes: 2
Views: 3920
Reputation: 322532
EDIT: Based on the comments below, it sounds like you want the color to alternate for each subsequent item that is clicked, and it can not be revered.
This should do it:
Example: http://jsfiddle.net/patrick_dw/zUdWq/
$('a').click((function() {
var i = 0;
var colors = ['blue','red'];
return function() {
$(this).addClass( colors[i = ++i % 2] ).unbind('click');
};
})());
This uses a closure to wrap around the variables. If you don't want/need that, here's the same thing without the closure.
Example: http://jsfiddle.net/patrick_dw/zUdWq/1/
var i = 0;
var colors = ['blue','red'];
$('a').click(function() {
$(this).addClass( colors[i = ++i % 2] ).unbind('click');
});
Original answer:
$a.addClass('red').click(function(){
$(this).toggleClass('red blue');
});
This will start by adding the red
class when the page loads, then will thereafter toggle red
and blue
upon each click.
If you wanted to start without any class on the item, then you could do this:
$a.click(function(){
if( !this.className ) {
this.className = 'red';
} else {
$(this).toggleClass('red blue');
}
});
Upvotes: 7