1

I'm very new at jQuery and have just been playing around with different things to try to get more comfortable. I have hit an issue here and haven't had luck fixing it despite looking for answers for a very long time.

I'm finding that the if/else statement will only execute the 'if'. So on the click, the square turns black, but afterwards it doesn't seem to accept any more clicks to change back to blue.

I found a lot of suggestions were to try .on('click', function(){ instead but that didn't change anything. I also tried another way I saw someone writing the css (({'background-color':'blue'})) but that didn't help either.

I know this is probably a really simple answer but, as mentioned, I'm new at this. I'd really appreciate any help at all.

Thank you.

$(document).ready(function(){
$('button').click(function () {
    if ($('.square').css('background-color', 'blue')) {
    $('.square').css('background-color', 'black');
    } else {
        $('.square').css('background-color', 'blue');
    }
});
});

& css

.square {
width: 100px;
height: 100px;
margin: 50px auto; 
background-color: blue;
}

& html

<div class="square"></div>
<button>click</button>

2 Answers 2

1
if ($('.square').css('background-color') === 'blue') {
    $('.square').css('background-color', 'black');
} else {
    $('.square').css('background-color', 'blue');
}

Your if statement was returning the JQuery selection of $('.square') because of the way JQuery chains work, and since objects are truthy, the if statement always evaluated instead of the else statement. Your function was not comparing the two values but rather assigning 'blue' the the background-color. This correction obtains the value of the background-color and compares it to 'blue' instead, and if they match it evaluates the if statement.

Here is the documentation on $().css() explaining the difference between the two function calls, and below is a demo of this code:

colorsEqual.canvas = document.createElement('canvas');
colorsEqual.canvas.width = colorsEqual.canvas.height = 1;
colorsEqual.context = colorsEqual.canvas.getContext('2d');

function colorsEqual(color1, color2){
  colorsEqual.context.fillStyle = color1;
  colorsEqual.context.fillRect(0, 0, 1, 1);
  
  var data1 = colorsEqual.context.getImageData(0, 0, 1, 1).data;
  
  colorsEqual.context.fillStyle = color2;
  colorsEqual.context.fillRect(0, 0, 1, 1);
  
  var data2 = colorsEqual.context.getImageData(0, 0, 1, 1).data;
  
  return (
    data1[0] == data2[0] &&
    data1[1] == data2[1] &&
    data1[2] == data2[2] &&
    data1[3] == data2[3]
  );
}

$(document).ready(function(){
  $('button').click(function () {
    if (colorsEqual($('.square').css('background-color'), 'blue')) {
      $('.square').css('background-color', 'black');
    } else {
      $('.square').css('background-color', 'blue');
    }
  });
});
.square {
  width: 100px;
  height: 100px;
  margin: 50px auto; 
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>
<button>click</button>

EDIT It turns out that another problem is the way getComputedStyle works. It doesn't necessarily return the CSS property the way it was authored and since it's browser dependent I added a way in the above code snippet to compare properly in all HTML5 compliant browsers using the Canvas API.

SECOND EDIT I'm providing a much simpler way of comparing color values that does not require the Canvas API in the below snippet. This is better because it does not depend on HTML5 compliancy.

$(document).ready(function(){
  $('button').click(function () {
    var $div = $('<div/>').addClass('square');
    $(document.body).append($div);
    if ($('.square').css('background-color') === $div.css('background-color')) {
      $('.square').css('background-color', 'black');
    } else {
      $('.square').css('background-color', 'blue');
    }
    $div.remove();
  });
});
.square {
  width: 100px;
  height: 100px;
  margin: 50px auto; 
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>
<button>click</button>

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

1 Comment

Hi Patrick, thanks for your suggestion. When I make that change, however, the square isn't updating the background-color at all, it just stays blue. Any idea why?
0

You need to check for the color value of the element, right now you are getting the object returned, and you need the background css value.

According to the jquery .css documentation the color value of the returned css can change.

Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as em, ex, px or % in a style sheet. Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).

Chrome, safari and firefox all returns colors as rgb, but there is always a chance that the test fails since the browser returns a wrong value.

A better way would be to toggle css classes, its a much safer way to change the color of a square since it is not browser dependent.

$(document).ready(function() {
  $('button').click(function() {
    $('.square').toggleClass("blue black");
  });
});
.square {
  width: 100px;
  height: 100px;
  margin: 50px auto;
}

.blue {
  background-color: blue;
}
.black {
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="square blue"></div>
<button>click</button>

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.