binga30
binga30

Reputation: 59

jquery adding hover to animation

I have a div that animates in and out on a continuous loop with this code:

$(document).ready(function() { 
setInterval(function () {
    $("#possum-animate").animate({
    bottom:"32"
    }, 3000 ).delay(10000).animate({
    bottom:"-70"
    }, 3000).delay(10000);
}, 10000);  
});

How can I add in a hover function so that if you hover the div it completes the animation to show, and then when you hover out it hides the div and starts the continuous loop again.

Upvotes: 0

Views: 79

Answers (2)

Sajjad Ashraf
Sajjad Ashraf

Reputation: 3844

You could do something like this

$(document).ready(function() { 

    function timeFunction(){

        var timeInterval = setInterval(function () {        

        $("#possum-animate").animate({

         bottom:"32"

    }, 3000 ).delay(10000).animate({

        bottom:"-70"

    }, 3000).delay(10000);

  }, 10000);     

return timeInterval;

}

// Start animating on page load

var timeInterval = timeFunction();

$("#possum-animate").bind({

    mouseenter: function(e){

        e.preventDefault();

        clearTimeout(timeInterval);
        $("#possum-animate").clearQueue(); 
        $("#possum-animate").stop();

    },

    mouseleave: function(e){

        e.preventDefault();

        timeInterval = timeFunction();

    } 

});

});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388326

Try

$(document).ready(function() {
    var flag = true;
    setInterval(function() {
                if (flag) {
                    $("#possum-animate").animate({
                                bottom : "32"
                            }, 3000).delay(10000).queue(function() {
                                $("#possum-animate").animate({
                                            bottom : "-70"
                                        }, 3000)
                            });
                }
            }, 10000);

    $("#possum-animate").hover(function() {
                flag = false;
                $(this).stop().animate({
                            bottom : "32"
                        }, 3000);
            }, function() {
                $(this).stop().animate({
                            bottom : "-70"
                        }, 3000);
                flag = true;
            });
});

Upvotes: 0

Related Questions