Home > Software design >  Change Background Color to red. and back to White on klick JavaScript
Change Background Color to red. and back to White on klick JavaScript

Time:10-08

I'm trying to change the background color of a div with class pole on click.

This is my code but it currently only changes from white to red but not back to white.

jQuery(".pole").on("click", function() {
    jQuery(this).css("background", "white");
    if (jQuery(this).css("background", "#ffffff")) {
        jQuery(this).css("background", "red");
    } else {
        jQuery(this).css("background", "white");
    }
});

I am using Oxygen Builder so they replace $ with jQuery.

CodePudding user response:

You have a few problems in your code. Your if statement isn't checking the value of the CSS background, its setting it. Plus the return value isn't #ffffff, its RGB(255, 255, 255);

But an easy solution is actually just toggle a class on and off. And set the default value on the original class.

jQuery(".pole").on("click", function() {
  jQuery(this).toggleClass("on");
})
.pole {
  width: 100px;
  height: 200px;
  border: 1px solid #000;
  background: red;
}

.pole.on{
  background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>

  • Related