Ramesh Pareek
Ramesh Pareek

Reputation: 1669

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.

Upvotes: 2

Views: 120

Answers (3)

JPacheco
JPacheco

Reputation: 83

You can use this code: (not very elegant but functional, LOL)

$(document).ready(function() {
  $('#b1').click(function() {
    var b = $(this);
    if (b.hasClass("red-class")) {
      b.removeClass("red-class");
      b.addClass("yellow-class");
    } else
    if (b.hasClass("yellow-class")) {
      b.removeClass("yellow-class");
      b.addClass("green-class");
    } else
    if (b.hasClass("green-class")) {
      b.removeClass("green-class");
      b.addClass("red-class");
    }
  });
});
body {
  padding: 5px;
}
label {
  font-weight: bold;
}
input[type=text] {
  width: 20em
}
p {
  margin: 1em 0 0;
}
.green-class {
  background-color: #2b542c;
}
.red-class {
  background-color: #ff0000;
}
.yellow-class {
  background-color: #ffff00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<label>Change Color in Button</label>
<button id="b1" class="green-class">Hello</button>


JsFiddle link

Upvotes: 0

Diogo Garcia
Diogo Garcia

Reputation: 27

A less elaborated approach could be:

JS (jQuery):

$(".toggledRed").click(function() {
    $(this).toggleClass("toggledYellow");
}); 


$(".toggledYellow").click(function() {
    $(this).toggleClass("toggledGreen");
}); 


$(".toggledGreen").click(function() {
    $(this).toggleClass("toggledRed");
}); 

CSS:

.toggledRed{
    background-color:#FF0000;
}

.toggledYellow{
    background-color:#FFFF00;
}

.toggledBlue{
    background-color:#0000FF;
}

And start your HTML with:

<div id="box" class="toggledRed"> 1 </div>

Should work.

Upvotes: 0

Ry-
Ry-

Reputation: 224859

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);
});

Upvotes: 10

Related Questions