Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

605
Views
Using Jquery, how to change color with if/else condition

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'});
        }
    });
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!