Home > Enterprise >  Using Jquery, how to change color with if/else condition
Using Jquery, how to change color with if/else condition

Time:04-22

In fact, I have 2 boxes, id named box1 and box2.

I am using J-query.

My design:

Click box1 => check box2 background color, if it is black, change it white, else change black.

My hard code:

<body>
<div id="box1"></div>
<div id="box2"></div>
</body>

$( document ).ready(function() {
    $("#box1").click(function(){
        if ($('#box2').css({backgroundColor: 'white'})) {
            $('#box2').css({backgroundColor: 'black'});
        } else {
            $('#box2').css({backgroundColor: 'white'});
        }
    });
});

CodePudding user response:

As you'll see in the snippet here, jQuery reports back the RGB value of the cell for it's background color. It's much easier to use classes for this kind of thing. in this case, you can just use toggleClass()

Also, for the record, your IF statement was malformed:

if ($('#box2').css({backgroundColor: 'white'})) {

should be

if ($('#box2').css('background-color') ==  'white') {

... but it would fail because it's actually rgb(255, 255, 255), not white

$(document).ready(function() {
  $("#box1").click(function() {
    console.log('The background color of box 2 is: ', $('#box2').css('background-color'))
    $("#box2").toggleClass('black');
  });
});
div {
  padding: 10px;
  display:inline-block;
  margin-right:10px;
  border: 1px solid #ccc;
  background-color: white;
}

.black {
  background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box1"></div>
<div id="box2"></div>

  • Related