[javascript] jQuery animate backgroundColor

I am trying to animate a change in backgroundColor using jQuery on mouseover.

I have checked some example and I seem to have it right, it works with other properties like fontSize, but with backgroundColor I get and "Invalid Property" js error. The element I am working with is a div.

$(".usercontent").mouseover(function() {
    $(this).animate({ backgroundColor: "olive" }, "slow");
});

Any ideas?

This question is related to javascript jquery colors jquery-animate

The answer is


If you wan't to animate your background using only core jQuery functionality, try this:

jQuery(".usercontent").mouseover(function() {
      jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
            jQuery(this).animate({
                backgroundColor: 'white'
            }, 'normal', 'linear', function() {
                jQuery(this).css({'background':'none', backgroundColor : ''});
            });
        });

For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.


Do it with CSS3-Transitions. Support is great (all modern browsers, even IE). With Compass and SASS this is quickly done:

#foo {background:red; @include transition(background 1s)}
#foo:hover {background:yellow}

Pure CSS:

#foo {
background:red;
-webkit-transition:background 1s;
-moz-transition:background 1s;
-o-transition:background 1s;
transition:background 1s
}
#foo:hover {background:yellow}

I've wrote an german article about this topic: http://www.solife.cc/blog/animation-farben-css3-transition.html


You can use 2 divs:

You could put a clone on top of it and fade the original out while fading the clone in.

When the fades are done, restore the original with the new bg.

$(function(){
    var $mytd = $('#mytd'), $elie = $mytd.clone(), os = $mytd.offset();

      // Create clone w other bg and position it on original
    $elie.toggleClass("class1, class2").appendTo("body")
         .offset({top: os.top, left: os.left}).hide();

    $mytd.mouseover(function() {            
          // Fade original
        $mytd.fadeOut(3000, function() {
            $mytd.toggleClass("class1, class2").show();
            $elie.toggleClass("class1, class2").hide();            
        });
          // Show clone at same time
        $elie.fadeIn(3000);
    });
});?

jsFiddle example


.toggleClass()
.offset()
.fadeIn()
.fadeOut()


ColorBlend plug in does exactly what u want

http://plugins.jquery.com/project/colorBlend

Here is the my highlight code

$("#container").colorBlend([{
    colorList:["white",  "yellow"], 
    param:"background-color",
    cycles: 1,
    duration: 500
}]);

Try this one:

(function($) {  

            var i = 0;  

            var someBackground = $(".someBackground");  
            var someColors = [ "yellow", "red", "blue", "pink" ];  


            someBackground.css('backgroundColor', someColors[0]);  

            window.setInterval(function() {  
                i = i == someColors.length ? 0 : i;  
                someBackground.animate({backgroundColor: someColors[i]}, 3000);  
                i++;  
            }, 30);  

})(jQuery);  

you can preview example here: http://jquerydemo.com/demo/jquery-animate-background-color.aspx


For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.


I stumbled across this page with the same issue, but the following problems:

  1. I can't include an extra jQuery plugin file with my current set-up.
  2. I'm not comfortable pasting large blocks of code that I don't have time to read over and validate.
  3. I don't have access to the css.
  4. I hardly had any time for implementation (it was only a visual improvement to an admin page)

With the above that pretty much ruled out every answer. Considering my fade of colour was very simple, I used the following quick hack instead:

element
  .css('color','#FF0000')
;
$('<div />')
  .css('width',0)
  .animate(
    {'width':100},
    {
      duration: 3000,
      step:function(now){
        var v = (255 - 255/100 * now).toString(16);
        v = (v.length < 2 ? '0' : '') + v.substr(0,2);
        element.css('color','#'+v+'0000');
      }
    }
  )
;

The above creates a temporary div that is never placed in the document flow. I then use jQuery's built-in animation to animate a numeric property of that element - in this case width - which can represent a percentage (0 to 100). Then, using the step function, I transfer this numeric animation to the text colour with a simple hex cacluation.

The same could have been achieved with setInterval, but by using this method you can benefit from jQuery's animation methods - like .stop() - and you can use easing and duration.

Obivously it's only of use for simple colour fades, for more complicated colour conversions you'll need to use one of the above answers - or code your own colour fade math :)


For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.


I had the same problem and fixed it by including jQuery UI. Here is the complete script :

<!-- include Google's AJAX API loader -->
<script src="http://www.google.com/jsapi"></script>
<!-- load JQuery and UI from Google (need to use UI to animate colors) -->
<script type="text/javascript">
google.load("jqueryui", "1.5.2");
</script>


<script type="text/javascript">
$(document).ready(function() {
$('#menu ul li.item').hover(
    function() {
        $(this).stop().animate({backgroundColor:'#4E1402'}, 300);
        }, function () {
        $(this).stop().animate({backgroundColor:'#943D20'}, 100);
    });
});
</script>

Try to use it

-moz-transition: background .2s linear;
-webkit-transition: background .2s linear;
-o-transition: background .2s linear;
transition: background .2s linear;

I stumbled across this page with the same issue, but the following problems:

  1. I can't include an extra jQuery plugin file with my current set-up.
  2. I'm not comfortable pasting large blocks of code that I don't have time to read over and validate.
  3. I don't have access to the css.
  4. I hardly had any time for implementation (it was only a visual improvement to an admin page)

With the above that pretty much ruled out every answer. Considering my fade of colour was very simple, I used the following quick hack instead:

element
  .css('color','#FF0000')
;
$('<div />')
  .css('width',0)
  .animate(
    {'width':100},
    {
      duration: 3000,
      step:function(now){
        var v = (255 - 255/100 * now).toString(16);
        v = (v.length < 2 ? '0' : '') + v.substr(0,2);
        element.css('color','#'+v+'0000');
      }
    }
  )
;

The above creates a temporary div that is never placed in the document flow. I then use jQuery's built-in animation to animate a numeric property of that element - in this case width - which can represent a percentage (0 to 100). Then, using the step function, I transfer this numeric animation to the text colour with a simple hex cacluation.

The same could have been achieved with setInterval, but by using this method you can benefit from jQuery's animation methods - like .stop() - and you can use easing and duration.

Obivously it's only of use for simple colour fades, for more complicated colour conversions you'll need to use one of the above answers - or code your own colour fade math :)


Try to use it

-moz-transition: background .2s linear;
-webkit-transition: background .2s linear;
-o-transition: background .2s linear;
transition: background .2s linear;

You can use jQuery UI to add this functionality. You can grab just what you need, so if you want to animate color, all you have to include is the following code. I got if from latest jQuery UI (currently 1.8.14)

/******************************************************************************/
/****************************** COLOR ANIMATIONS ******************************/
/******************************************************************************/

// override the animation for color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor',
    'borderRightColor', 'borderTopColor', 'borderColor', 'color', 'outlineColor'],
function(i, attr) {
    $.fx.step[attr] = function(fx) {
        if (!fx.colorInit) {
            fx.start = getColor(fx.elem, attr);
            fx.end = getRGB(fx.end);
            fx.colorInit = true;
        }

        fx.elem.style[attr] = 'rgb(' +
            Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0) + ',' +
            Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0) + ',' +
            Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0) + ')';
    };
});

// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/

// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
                return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
                return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
                return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
                return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
                return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Look for rgba(0, 0, 0, 0) == transparent in Safari 3
        if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
                return colors['transparent'];

        // Otherwise, we're most likely dealing with a named color
        return colors[$.trim(color).toLowerCase()];
}

function getColor(elem, attr) {
        var color;

        do {
                color = $.curCSS(elem, attr);

                // Keep going until we find an element that has color, or we hit the body
                if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
                        break;

                attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
};

It's only 1.43kb after compressing with YUI:

$.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,a){$.fx.step[a]=function(c){if(!c.colorInit){c.start=getColor(c.elem,a);c.end=getRGB(c.end);c.colorInit=true}c.elem.style[a]="rgb("+Math.max(Math.min(parseInt((c.pos*(c.end[0]-c.start[0]))+c.start[0],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[1]-c.start[1]))+c.start[1],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[2]-c.start[2]))+c.start[2],10),255),0)+")"}});function getRGB(b){var a;if(b&&b.constructor==Array&&b.length==3){return b}if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b)){return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)]}if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b)){return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55]}if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b)){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)]}if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b)){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)]}if(a=/rgba\(0, 0, 0, 0\)/.exec(b)){return colors.transparent}return colors[$.trim(b).toLowerCase()]}function getColor(c,a){var b;do{b=$.curCSS(c,a);if(b!=""&&b!="transparent"||$.nodeName(c,"body")){break}a="backgroundColor"}while(c=c.parentNode);return getRGB(b)};

You can also animate colors using CSS3 transitions but it's only supported by modern browsers.

a.test {
  color: red;
  -moz-transition-property: color;  /* FF4+ */
  -moz-transition-duration: 1s;
  -webkit-transition-property: color;  /* Saf3.2+, Chrome */
  -webkit-transition-duration: 1s;
  -o-transition-property: color;  /* Opera 10.5+ */
  -o-transition-duration: 1s;
  -ms-transition-property: color;  /* IE10? */
  -ms-transition-duration: 1s;
  transition-property: color;  /* Standard */
  transition-duration: 1s;
  }

  a.test:hover {
  color: blue;
  }

Using shorthand property:

/* shorthand notation for transition properties */
/* transition: [transition-property] [transition-duration] [transition-timing-function] [transition-delay]; */

a.test {
  color: red;
  -moz-transition: color 1s;
  -webkit-transition: color 1s;
  -o-transition: color 1s;
  -ms-transition: color 1s;
  transition: color 1s;
  }

a.test {
  color: blue;
 }

Unlike regular javascript transitions, CSS3 transitions are hardware accelerated and therefore smoother. You can use Modernizr, to find out if the browser supports CSS3 transitions, if it didn't then you can use jQuery as a fallback:

if ( !cssTransitions() ) {
    $(document).ready(function(){
        $(".test").hover(function () {
                $(this).stop().animate({ backgroundColor: "red" },500)
             }, function() {
                 $(this).stop().animate({ backgroundColor: "blue" },500)}    
             );
    }); 
}

Remember to use stop() to stop the current animation before starting a new one otherwise when you pass over the element too fast, the effect keeps blinking for a while.


I used a combination of CSS transitions with JQuery for the desired effect; obviously browsers which don't support CSS transitions will not animate but its a lightweight option which works well for most browsers and for my requirements is acceptable degradation.

Jquery to change the background color:

   $('.mylinkholder a').hover(
        function () {
            $(this).css({ backgroundColor: '#f0f0f0' }); 
        },
        function () {
            $(this).css({ backgroundColor: '#fff' });
        }
    );

CSS using transition to fade background-color change

   .mylinkholder a
   {
   transition: background-color .5s ease-in-out;
   -moz-transition: background-color .5s ease-in-out;
   -webkit-transition: background-color .5s ease-in-out; 
  -o-transition: background-color .5s ease-in-out; 
   }

These days jQuery color plugin supports following named colors:

aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]

I had the same problem and fixed it by including jQuery UI. Here is the complete script :

<!-- include Google's AJAX API loader -->
<script src="http://www.google.com/jsapi"></script>
<!-- load JQuery and UI from Google (need to use UI to animate colors) -->
<script type="text/javascript">
google.load("jqueryui", "1.5.2");
</script>


<script type="text/javascript">
$(document).ready(function() {
$('#menu ul li.item').hover(
    function() {
        $(this).stop().animate({backgroundColor:'#4E1402'}, 300);
        }, function () {
        $(this).stop().animate({backgroundColor:'#943D20'}, 100);
    });
});
</script>

For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.


I like using delay() to get this done, here's an example:

jQuery(element).animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);

This can be called by a function, with "element" being the element class/name/etc. The element will instantly appear with the #FCFCD8 background, hold for a second, then fade into #EFEAEA.


Simply add the following snippet bellow your jquery script and enjoy:

<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>

See the example

Reference for more info


I like using delay() to get this done, here's an example:

jQuery(element).animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);

This can be called by a function, with "element" being the element class/name/etc. The element will instantly appear with the #FCFCD8 background, hold for a second, then fade into #EFEAEA.


Bitstorm has the best jquery color animation plugin I've seen. It's an improvement to the jquery color project. It also supports rgba.

http://www.bitstorm.org/jquery/color-animation/


I used a combination of CSS transitions with JQuery for the desired effect; obviously browsers which don't support CSS transitions will not animate but its a lightweight option which works well for most browsers and for my requirements is acceptable degradation.

Jquery to change the background color:

   $('.mylinkholder a').hover(
        function () {
            $(this).css({ backgroundColor: '#f0f0f0' }); 
        },
        function () {
            $(this).css({ backgroundColor: '#fff' });
        }
    );

CSS using transition to fade background-color change

   .mylinkholder a
   {
   transition: background-color .5s ease-in-out;
   -moz-transition: background-color .5s ease-in-out;
   -webkit-transition: background-color .5s ease-in-out; 
  -o-transition: background-color .5s ease-in-out; 
   }

If you wan't to animate your background using only core jQuery functionality, try this:

jQuery(".usercontent").mouseover(function() {
      jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
            jQuery(this).animate({
                backgroundColor: 'white'
            }, 'normal', 'linear', function() {
                jQuery(this).css({'background':'none', backgroundColor : ''});
            });
        });

Try this one:

(function($) {  

            var i = 0;  

            var someBackground = $(".someBackground");  
            var someColors = [ "yellow", "red", "blue", "pink" ];  


            someBackground.css('backgroundColor', someColors[0]);  

            window.setInterval(function() {  
                i = i == someColors.length ? 0 : i;  
                someBackground.animate({backgroundColor: someColors[i]}, 3000);  
                i++;  
            }, 30);  

})(jQuery);  

you can preview example here: http://jquerydemo.com/demo/jquery-animate-background-color.aspx


These days jQuery color plugin supports following named colors:

aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]

Try this one:

jQuery(".usercontent").hover(function() {
    jQuery(this).animate({backgroundColor:"pink"}, "slow");
},function(){
    jQuery(this).animate({backgroundColor:"white"}, "slow");
});

Revised way with effects:

jQuery(".usercontent").hover(function() {

    jQuery(this).fadeout("slow",function(){
        jQuery(this).animate({"color","yellow"}, "slow");
    });
});

Bitstorm has the best jquery color animation plugin I've seen. It's an improvement to the jquery color project. It also supports rgba.

http://www.bitstorm.org/jquery/color-animation/


You can use jQuery UI to add this functionality. You can grab just what you need, so if you want to animate color, all you have to include is the following code. I got if from latest jQuery UI (currently 1.8.14)

/******************************************************************************/
/****************************** COLOR ANIMATIONS ******************************/
/******************************************************************************/

// override the animation for color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor',
    'borderRightColor', 'borderTopColor', 'borderColor', 'color', 'outlineColor'],
function(i, attr) {
    $.fx.step[attr] = function(fx) {
        if (!fx.colorInit) {
            fx.start = getColor(fx.elem, attr);
            fx.end = getRGB(fx.end);
            fx.colorInit = true;
        }

        fx.elem.style[attr] = 'rgb(' +
            Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0) + ',' +
            Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0) + ',' +
            Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0) + ')';
    };
});

// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/

// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
                return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
                return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
                return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
                return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
                return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Look for rgba(0, 0, 0, 0) == transparent in Safari 3
        if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
                return colors['transparent'];

        // Otherwise, we're most likely dealing with a named color
        return colors[$.trim(color).toLowerCase()];
}

function getColor(elem, attr) {
        var color;

        do {
                color = $.curCSS(elem, attr);

                // Keep going until we find an element that has color, or we hit the body
                if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
                        break;

                attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
};

It's only 1.43kb after compressing with YUI:

$.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,a){$.fx.step[a]=function(c){if(!c.colorInit){c.start=getColor(c.elem,a);c.end=getRGB(c.end);c.colorInit=true}c.elem.style[a]="rgb("+Math.max(Math.min(parseInt((c.pos*(c.end[0]-c.start[0]))+c.start[0],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[1]-c.start[1]))+c.start[1],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[2]-c.start[2]))+c.start[2],10),255),0)+")"}});function getRGB(b){var a;if(b&&b.constructor==Array&&b.length==3){return b}if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b)){return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)]}if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b)){return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55]}if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b)){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)]}if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b)){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)]}if(a=/rgba\(0, 0, 0, 0\)/.exec(b)){return colors.transparent}return colors[$.trim(b).toLowerCase()]}function getColor(c,a){var b;do{b=$.curCSS(c,a);if(b!=""&&b!="transparent"||$.nodeName(c,"body")){break}a="backgroundColor"}while(c=c.parentNode);return getRGB(b)};

You can also animate colors using CSS3 transitions but it's only supported by modern browsers.

a.test {
  color: red;
  -moz-transition-property: color;  /* FF4+ */
  -moz-transition-duration: 1s;
  -webkit-transition-property: color;  /* Saf3.2+, Chrome */
  -webkit-transition-duration: 1s;
  -o-transition-property: color;  /* Opera 10.5+ */
  -o-transition-duration: 1s;
  -ms-transition-property: color;  /* IE10? */
  -ms-transition-duration: 1s;
  transition-property: color;  /* Standard */
  transition-duration: 1s;
  }

  a.test:hover {
  color: blue;
  }

Using shorthand property:

/* shorthand notation for transition properties */
/* transition: [transition-property] [transition-duration] [transition-timing-function] [transition-delay]; */

a.test {
  color: red;
  -moz-transition: color 1s;
  -webkit-transition: color 1s;
  -o-transition: color 1s;
  -ms-transition: color 1s;
  transition: color 1s;
  }

a.test {
  color: blue;
 }

Unlike regular javascript transitions, CSS3 transitions are hardware accelerated and therefore smoother. You can use Modernizr, to find out if the browser supports CSS3 transitions, if it didn't then you can use jQuery as a fallback:

if ( !cssTransitions() ) {
    $(document).ready(function(){
        $(".test").hover(function () {
                $(this).stop().animate({ backgroundColor: "red" },500)
             }, function() {
                 $(this).stop().animate({ backgroundColor: "blue" },500)}    
             );
    }); 
}

Remember to use stop() to stop the current animation before starting a new one otherwise when you pass over the element too fast, the effect keeps blinking for a while.


Simply add the following snippet bellow your jquery script and enjoy:

<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>

See the example

Reference for more info


Try this one:

jQuery(".usercontent").hover(function() {
    jQuery(this).animate({backgroundColor:"pink"}, "slow");
},function(){
    jQuery(this).animate({backgroundColor:"white"}, "slow");
});

Revised way with effects:

jQuery(".usercontent").hover(function() {

    jQuery(this).fadeout("slow",function(){
        jQuery(this).animate({"color","yellow"}, "slow");
    });
});

ColorBlend plug in does exactly what u want

http://plugins.jquery.com/project/colorBlend

Here is the my highlight code

$("#container").colorBlend([{
    colorList:["white",  "yellow"], 
    param:"background-color",
    cycles: 1,
    duration: 500
}]);

You can use 2 divs:

You could put a clone on top of it and fade the original out while fading the clone in.

When the fades are done, restore the original with the new bg.

$(function(){
    var $mytd = $('#mytd'), $elie = $mytd.clone(), os = $mytd.offset();

      // Create clone w other bg and position it on original
    $elie.toggleClass("class1, class2").appendTo("body")
         .offset({top: os.top, left: os.left}).hide();

    $mytd.mouseover(function() {            
          // Fade original
        $mytd.fadeOut(3000, function() {
            $mytd.toggleClass("class1, class2").show();
            $elie.toggleClass("class1, class2").hide();            
        });
          // Show clone at same time
        $elie.fadeIn(3000);
    });
});?

jsFiddle example


.toggleClass()
.offset()
.fadeIn()
.fadeOut()


Do it with CSS3-Transitions. Support is great (all modern browsers, even IE). With Compass and SASS this is quickly done:

#foo {background:red; @include transition(background 1s)}
#foo:hover {background:yellow}

Pure CSS:

#foo {
background:red;
-webkit-transition:background 1s;
-moz-transition:background 1s;
-o-transition:background 1s;
transition:background 1s
}
#foo:hover {background:yellow}

I've wrote an german article about this topic: http://www.solife.cc/blog/animation-farben-css3-transition.html


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to colors

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme?

Examples related to jquery-animate

jQuery .scrollTop(); + animation CSS rotation cross browser with jquery.animate() jquery toggle slide from left to right and back How to animate CSS Translate jQuery animate margin top animating addClass/removeClass with jQuery Animate scroll to ID on page load Change text (html) with .animate jquery animate background position Animate element to auto height with jQuery