Unknown developer
Unknown developer

Reputation: 5970

Onclick change background 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 it does not work??

Thank you very much

http://jsfiddle.net/m73faf4g/

Upvotes: 3

Views: 2072

Answers (3)

scniro
scniro

Reputation: 16989

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 wish :

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


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

Alternative Fiddle

Upvotes: 5

adeneo
adeneo

Reputation: 318342

Create a toggle function that doesn't rely on the color, as the returned style can be inconsistent in different browsers depending on wether they support 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

Upvotes: 1

neo
neo

Reputation: 579

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 css() function returns rgb formatted color which won't work with your conditions.

Upvotes: 1

Related Questions