Background color to change Onclick color

Here is my JQuery code:

$("#test").click(function() {
      if($(this).css("background-color")=="#FFFFFF") 
         $(this).css("background-color","blue");
     else
         if($(this).css("background-color")=="blue")
              $(this).css("background-color","#FFFFFF");
    });

      

and here is the HTML:

<div id="test">
    click me!
</div>

      

Can you explain to me why this doesn't work?

Many thanks

http://jsfiddle.net/m73faf4g/

+3


source to share


3 answers


You also forgot to include JQuery in your fiddle

Updated Fiddle

$(function(){
    $('#test').click(function() {
       if($(this).css('background-color') == 'rgb(255, 255, 255)')
          $(this).css('background-color', 'blue');
       else
          if($(this).css('background-color') == 'rgb(0, 0, 255)')
              $(this).css('background-color', '#FFFFFF');
    });
});

      



Edit



Alternative way if you like:

.blue {
    background-color: blue !important;
}

      


$(function(){
    $('#test').click(function() {
        $(this).toggleClass('blue');
    });
});

      

Alternative script

+5


source


use it like this:

$("#test").click(function() {
    if($(this).css("background-color")=="rgb(255, 255, 255)") 
        $(this).css("background-color","blue");
    else
        if($(this).css("background-color")=="rgb(0, 0, 255)")
            $(this).css("background-color","#FFFFFF");
});

      



the reason is that the function is css()

returning a rgb

formatted color which won't work with your conditions.

+1


source


Create a toggle function that doesn't rely on color, as the returned style can be inconsistent across browsers depending on whether they are supported by rgb / rgba / hsl, etc.

$("#test").on('click', function() {

    var flag = $(this).data('flag');

    $(this).css('background-color', flag ? '#fff' : 'blue');

    $(this).data('flag', !flag);
});

      

FIDDLE

+1


source







All Articles