• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

524
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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error