I want a toggle button with it's current css background-color value as 'red'. on first click it should change to 'yellow', on second click it changes to 'green', and on third it should change back to 'red'.
HTML
<div id="box" class="boxa"> 1 </div>
Javascript:
$('div[id="box"]').mousedown(function(){
if($(this).css ('background-color', 'red')) {
$(this).css ('background-color', 'yellow');
}
});
But this doesn't work as $(this).css ('background-color', 'red') always returns true,
then tried storing the value in a variable and then checking like this
var color = $(this).css ('background-color');
if (color=="red") {
// change it to some other color
}
But this doesn't work either as color returns value in RGB.
Can anyone help me write a working solution.
Rather than checking the current colour, know the current colour!
var colors = ['red', 'yellow', 'green'];
var currentColor = 0;
Then the change becomes nice and straightforward:
$('#box').mousedown(function () {
currentColor++;
var newColor = colors[currentColor % colors.length];
$(this).css('background-color', newColor);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With