Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make a Toggle button in javascript

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.

like image 848
Ramesh Pareek Avatar asked Jul 25 '26 18:07

Ramesh Pareek


1 Answers

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);
});
like image 80
Ry- Avatar answered Jul 28 '26 09:07

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!