0

I need to build a very simple piece of code for when you click a <td> it will turn black but when you click it again it will turn white.

$(document).ready(function(){
    $("td").click(function(){
        if($(this).css('background-color') != 'black'){
            $(this).css('background-color', 'black');
        }
        else if($(this).css('background-color') === 'black'){
            $(this).css('background-color', 'white');
        }
    });
});

With this code it will turn black but wont turn white again.

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

3

It won't turn white again because "black" is just a shortcut. The browser is converting that to rgb(0, 0, 0) which is not absolutely-strictly-equal (== vs. ===) to "black"

See this fiddle:

https://jsfiddle.net/uxnrfh3c/

$(document).ready(function() {
    $("span").click(function() {
        alert($(this).css('background-color')); // alerts rgb(0, 0, 0)
        if($(this).css('background-color') != 'black') {
            $(this).css('background-color', 'black');
        }
        else if($(this).css('background-color') === 'black') {
            $(this).css('background-color', 'white');
        }
    });
});
Community
  • 1
  • 1
  • this works for chrome but not firefox that is the only issue – Ricky_Woessner Apr 21 '17 at 17:07
  • @Ricky_Woessner Then you can't detect the color this way and need to store your state somewhere else, like in Ilya Zinkevych's answer. Or do multiple checks, `if(color == rgb(0,0,0) || coloor == "black")` (or whatever Firefox treats the value as). There are a lot of options here. I've given you why it doesn't work AND a metehod to figure out what the value IS, its up to you now to take that information and fix your implementation. – Draco18s no longer trusts SE Apr 21 '17 at 17:10
1

Why don't you make a flag which coresponds to state of your element:

$(document).ready(function(){
  let state = true;
  $("td").click(function(){
    if(state) {
      $(this).css('background-color', 'black');
      state = false;
    } else {
      $(this).css('background-color', 'white');
      state = true;
    }
  });
});