Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate to transparent

$(".block li").hover(
    function(){
        $(this).animate({backgroundColor: "#000"});
    },
    function(){
        $(this).animate({backgroundColor: "#fff"});
    }
);

Need to change #fff to no color. Animation should occur from #000 to transparent.

Any solution?

like image 838
James Avatar asked Sep 09 '10 19:09

James


People also ask

Is jQuery slower for animations?

jQuery can be several times slower than CSS when talking about animations. CSS animations and transitions have the advantage of being hardware accelerated by the GPU, which is really good in moving pixels.

What is fadeTo?

Definition and Usage. The fadeTo() method gradually changes the opacity, for selected elements, to a specified opacity (fading effect).

Is jQuery used for animation?

With jQuery, you can create custom animations.

How you can use jQuery to animate a flash to the button?

The solution to Jquery To Animate A Flash To The Button Selected will be demonstrated using examples in this article. $("#someElement"). fadeOut(100). fadeIn(100).


2 Answers

You could use rgba(...) (see browser support here).

var elem = $('#foo')[0];

$({
    r: 0,
    g: 0,
    b: 0,
    a: 1
}).animate({
    a: 0
}, {
    step: function() {
        elem.style.backgroundColor =
            'rgba(' +
                ~~this.r + ',' + ~~this.g + ',' + ~~this.b + ',' +
                ~~(this.a*100)/100 +
            ')';
    },
    duration: 1000
});​

~~ is to floor values, otherwise you'll end up with stuff like rgba(0.1029302....

like image 180
James Avatar answered Oct 03 '22 13:10

James


Instead of changing background color, remove that attribute!

The code is as simple as:

$("li").hover(
    function(){
        $(this).toggleClass('hover', 1000);
    },
    function(){
        $(this).toggleClass('hover', 2000);
    }
);

Example: http://jsfiddle.net/rdWTE/

For it to work, you need jQuery and jQuery UI. Does exactly what you wanted (except the colors)!

Those numbers in jQuery script stand for animation duration in milliseconds.

EDIT:

Uhm... Found out that toggleClass can bug from time to time. Better to use addClass on hover, and removeClass on mouse out.

like image 38
tomsseisums Avatar answered Oct 03 '22 14:10

tomsseisums