1

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

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.