Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  49] [ 2]  / answers: 1 / hits: 83696  / 11 Years ago, thu, august 8, 2013, 12:00:00

I have a box without color. if the box is being click() it will addClass('.red') to make it red, and if click again the box color change to blue. they change alternatively. and I don't know how to make it.



Code



HTML



<div class='box'></div>


CSS



.box {          
width: 250px;
height: 100px;
border: 1px #000 solid;
}

.red {
background: red;
}

.blue {
background: blue;
}


Javascript



$('div').click(function() {
$(this).addClass('red');
});


link of jsfiddle


More From » jquery

 Answers
56

Try with toggleClass like



$('div').click(function() {
$(this).toggleClass(red);
});


If you want to toggle 2 classes red and blue then use like



$('div').click(function() {
$(this).toggleClass(red blue);
});

[#76466] Tuesday, August 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lidialyrick

Total Points: 737
Total Questions: 104
Total Answers: 89

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;