Reputation: 5970
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
Upvotes: 3
Views: 2072
Reputation: 16989
You also forgot to include JQuery in your 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');
});
});
Alternative Way, if you wish :
.blue {
background-color: blue !important;
}
$(function(){
$('#test').click(function() {
$(this).toggleClass('blue');
});
});
Upvotes: 5
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);
});
Upvotes: 1
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