Sam Murphey
Sam Murphey

Reputation: 338

Stopping a div animation from being triggered in the future

I have a pretty wide div that goes over the width of the page. I want there to be a function where people can hover their mouse over the div and it will animate the margins so that it moves and you can see the rest of the content. I already have a working script for this:

var busy = 0;
$('#busy').html(busy);
    $("#hover").hover(
    //on mouseover
    function() {
        if(!busy){
        busy=1;
            $('#busy').html(busy);
            $('#tooltip').fadeOut('slow');
            $('#slide').animate({
                marginLeft: '-3415px' //substracts 184px
            }, 15100
            );
            $('#busy').html(busy);
        }

    },
    //on mouseout
    function() {
            $('#slide').animate({
                marginLeft: '-683px' //substracts 184px
            }, 11100, busy =0
            );
            $('#tooltip').fadeIn('slow');
            $('#busy').html(busy);
    }
  );

but it bugs out. The animation itself works just fine, but if you move your mouse over and out over the div multiple times while it's animating it saves all those movements and will continue to animate it later even when the user is not interacting with it. Like it's queuing up all of the mouse-over events. I tried to fix that with the 'busy' variable, but that doesn't seem to be doing anything. Any suggestions?

Upvotes: 0

Views: 156

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113485

You just need to use stop() function adding it before calling animation functions like animate() or fadeIn().

$('#busy').html(busy);
    $("#hover").hover(
    //on mouseover
    function() {
        if(!busy){
        busy=1;
            $('#busy').html(busy);
            $('#tooltip').stop(true).fadeOut('slow');
            //            ^^^^^^^^^^ Here
            $('#slide').stop(true).animate({
            //          ^^^^^^^^^^ Here
                marginLeft: '-3415px' //substracts 184px
            }, 15100
            );
            $('#busy').html(busy);
        }

    },
    //on mouseout
    function() {
            $('#slide').stop(true).animate({
            //          ^^^^^^^^^^ Here
                marginLeft: '-683px' //substracts 184px
            }, 11100, busy =0
            );
            $('#tooltip').stop(true).fadeIn('slow');
            //            ^^^^^^^^^^ Here
            $('#busy').html(busy);
    }
  );

.stop()

Description: Stop the currently-running animation on the matched elements.

.stop( [clearQueue ] [, jumpToEnd ] )

Upvotes: 2

Related Questions