Search code examples
javascriptjqueryanimationmouseovermouseout

jquery .animate() mouseover / mousout


I have a div which is animated to fluidly change position in a designated area. This works nicely. Now i would like the animation to pause on mouseover and resume on mouseout plus have the div enlarge on mouseover and resize to former small size on mouseout.

My code looks like the following:

function animateBubble(canvas, bubble){

    newB = newSize();
    newQ = newPosition(canvas, bubble);
    oldQ = $(bubble).offset();
    speed = calcSpeed([oldQ.top, oldQ.left], newQ);

    $(bubble).animate({ // initial animation start of bubble
        top: newQ[0],
        left: newQ[1],
        width: newB[0],
        height: newB[1]
    },
    {   duration: speed, // set the duration
        step: function( now, fx ) { // get the coordinates of the bubble dynamically
            var offset = $(this).offset();
            xPos = offset.left; // now position
            yPos = offset.top;
            nowWidth = $(this).width();
            nowHeight = $(this).height();
        },
        complete: function(){ // do the whole animation again upon completion
            animateBubble(canvas, bubble);
        }
    }).mouseover(function(){ // pause animation on mouseover
        $(bubble).stop();
        $(bubble).height(230);
        $(bubble).width(230);
        }).mouseleave(function(){ // restart animation on mouseout
            //alert('hello');
            $(this).height(nowHeight);
            $(this).width(nowWidth);
            $(this).start();
            animateBubble(canvas, bubble); // doesn't want to start again
        });
}

It seems that the on mouseout I can either resume the animation without resizing the div, or resize the div without resuming animation.

Can someone help me with this one ?

here is a working js fiddle

http://jsfiddle.net/29cwcx04/

thanx


Solution

  • The problem, I believe, is that your cutting the width and height animation before its done re-sizing the circle back to the normal size. Here´s a quick fix:

    ...mouseleave(function(){ // restart animation on mouseout
                //alert('hello');
                $(this).height(nowHeight);
                $(this).width(nowWidth);
                setTimeout(function(){animateBubble(canvas, bubble);},1000); 
            });