user3058067
user3058067

Reputation: 327

Javascript animate image, slide up bug

I have an sliding image and I have a problem it it. If you do fast mouseover over the images multiple times and then you get the mouse outside pics it still animates. Somehow it records and plays the animation even after you are not with mouse over it. Here is my code and link to check it:

<script type="text/javascript">
$(document).ready(function() {
    $('.col-md-4,.col-xs-4').hover( 
    function () {
        $(this).find('#hoverpic').animate({ "top": "-=330px" }, "normal" );
    },
    function () {
        $(this).find('#hoverpic').animate({ "top": "+=330px" }, "normal" );
    });
});
</script>   

Upvotes: 1

Views: 88

Answers (4)

doku
doku

Reputation: 36

You need to make a simple change (see commented code) if you want to avoid the jumping image when hovering out before the animation finishes:

$('.col-md-4,.col-xs-4').hover(
function () {
    $(this).find('#hoverpic').stop().animate(
    { "top": "0px" } //WAS -=330px
    , "normal" );
},
function () {
    $(this).find('#hoverpic').stop().animate({ 
    "top": "330px" //WAS +=330px
    }, "normal" );
});

Upvotes: 0

Skwal
Skwal

Reputation: 2160

I usually add a class while it's animating. Something like this:

$(document).ready(function() {
    $('.col-md-4,.col-xs-4').hover( 
    function () {
        if(!$(this).hasClass('animate')) {
            $(this).addClass('animate');
            $(this).find('#hoverpic').animate({ "top": "-=330px" }, "normal" );
        }
    },
    function () {
        if($(this).hasClass('animate')) {
            $(this).find('#hoverpic').animate({ "top": "+=330px" }, "normal", function() { $(this).removeClass('animate'); } );
        }
    });
});

Upvotes: 1

Mike
Mike

Reputation: 894

you should put a check for

if( $(elem).is(':animated') ) {...}

in your code.

<script type="text/javascript">
$(document).ready(function() {
    $('.col-md-4,.col-xs-4').hover( 
    function () {
        if(!$(this).is(':animated'))
        $(this).find('#hoverpic').animate({ "top": "-=330px" }, "normal" );
    },
    function () {
        if($(this).is(':animated'))
        $(this).find('#hoverpic').animate({ "top": "+=330px" }, "normal" );
    });
});
</script>  

Upvotes: 1

CRABOLO
CRABOLO

Reputation: 8793

add .stop()

   function () {
        $(this).find('#hoverpic').stop().animate({ "top": "-=330px" }, "normal" );
    },
    function () {
        $(this).find('#hoverpic').stop().animate({ "top": "+=330px" }, "normal" );
    });

if .stop() doesn't work well enough

you can try with .stop(true) or .stop(true, true)

http://api.jquery.com/stop

Upvotes: 2

Related Questions