Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change Background Color to red. and back to White on klick JavaScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 class="pole"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading