Victor Ionescu
Victor Ionescu

Reputation: 985

Stopping and restarting an animation on hover in jQuery

I'm trying to create an animated button using jQuery that should stop on hover and then restart when it's not hovered.

For the animation I'm using a loop that looks like this:

$(document).ready(function test() {
        $('#box').animate({opacity:0.5}, {duration:750})
        .animate({opacity:1}, {duration:1500})
        .animate({opacity:0.5}, {duration:750, complete: test})
        ;
    });

And I tried adding a hover with a .stop() but, then I don't know how to restart the animation. Do you have any suggestions?

Also, I have a little example of this here: http://jsfiddle.net/fTpZZ/

Upvotes: 0

Views: 1037

Answers (2)

David Horák
David Horák

Reputation: 5565

Working solution: (http://jsfiddle.net/fTpZZ/50/)

$(document).ready(function()
    {
        $('#box').hover(function() {                   
            $('#box').stop();
            $('#box').animate({opacity:0},1);
        });

        function foo()
        {
            $('#box').animate({opacity:0.5}, 750, function(){
                $('#box').animate({opacity:1}, 1500, function(){
                    $('#box').animate({opacity:0.5}, 750, foo());    
                });
            });             
        }

        foo();          
    });

Upvotes: 1

Chris Serra
Chris Serra

Reputation: 13546

the hover() event handler can handle a handlerIn and handlerOut method as the first and second arguments, respectively.

hover( handlerIn(eventObject), handlerOut(eventObject) )

Create 2 separate functions--one for the "on" state, and one for the "off"

.hover() - jQuery API

Upvotes: 2

Related Questions