0

I am trying to toggle the background color of same div. It does changes once (from blue to red) as expected. But it is not able to toggle back to red and continue toggling between the 2 colors. I know I should use "==" in the first if-statement but when using "==" not even the first toggle works.

Any suggestions how to get the toggle to work repetitive?

function toggleFunction() {
  var x = document.getElementById("box");
  
  if (x.style.background == "blue") {
    x.style.background = "red";
  } else {
    x.style.background = "blue";
 }
}
.box {
  background-color: blue;
  width: 100px;
  height: 100px;
  margin: 30px 0px 0px 30px;
}
<div id="box" class="box" onclick="toggleFunction()"></div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
Toolbox
  • 2,333
  • 12
  • 26

2 Answers2

2

The simplest solution would to create a new class called red and toggle that using classList.toggle. The main advantage of this approach would be that you can toggle more CSS properties, if you use a class for toggling and this will also deduct the if-else comparison for you.

function toggleFunction() {
  var x = document.getElementById("box");
  x.classList.toggle("red");
}
.box {
  background-color: blue;
  width: 100px;
  height: 100px;
  margin: 30px 0px 0px 30px;
}
.red{
 background-color: red;
}
<div id="box" class="box" onclick="toggleFunction()"></div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

$( ".box" ).each(function() {
  $( this).click(function() {
    $( this ).toggleClass( "red" );
  });
});
.box {
  background: blue;
  width: 100px;
  height: 100px;
  margin: 30px 0px 0px 30px;
}
.box.red {
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box" class="box"></div>

<div id="box" class="box"></div>
siwakorn
  • 417
  • 4
  • 10