jQuery Gives us RGB, not HEX
jQuery will return an rgb
value for #CCC
when requested. For example, if you set the background color to #CCC
, and then requested it with jQuery:
$(".foo").css("backgroundColor"); // rgb(204, 204, 204)
Getting HEX from RGB
This means you'll need to have a means by which to convert the rgb back into HEX. This question has been asked and answered, here on Stack Overflow. See Get HEX value rather than RGB value with jQuery. For our purposes we can use the function below:
//Function to convert hex format to a rgb color
function rgb2hex(rgb){
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}
Making Smooth backgroundColor Animations Possible
That would take care of the retrieval, and the comparison. Next you'll need to load in the jQuery UI core which extends the $.animate()
method just a bit.
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui..."></script>
Animating the Background Color
With jQuery UI's core inplace (full path here), you can do the following:
$(".foo").animate({ backgroundColor: "#999999" }, 1000);
This will gradually animate the background from whatever it is to begin with, to #999999
, over the time of one second.
All Together Now
So in the end we have the following (assumes jQuery UI's core is linked):
//Function to convert hex format to a rgb color
function rgb2hex(rgb){
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}
$("#hello").on("click", function(e){
background = rgb2hex( $(this).css("backgroundColor") );
if ( background == '#cccccc' ) {
$(this).animate({
backgroundColor: "#123456",
color: "#fff"
}, 1000);
}
});
Online Demo: http://jsbin.com/uwiyon/edit#javascript,html