moey
moey

Reputation: 10887

jQuery Animation: Stop Animating Once Mouse Out

I am trying to make a div to slide out and in upon hover i.e. mouse enter and leave, respectively. However, when I hovered in and out several times, the div kept sliding back and forth basically up to the number of times I did the hover. Please refer to this jsFiddle example.

As you've probably guessed, I am hoping to make the div stop (i.e. slided in) once the mouse is outside of the element regardless how many times I've moused over it. I think there is something missing in my understanding about jQuery animation.

$("#state-slider").hover(function() {
  $(this).animate({
    left: '0'
  }, 500);
}, function() {
  $(this).animate({ left: "-270" }, 500);
});

Thank you.

Upvotes: 5

Views: 11010

Answers (3)

Tomas Aschan
Tomas Aschan

Reputation: 60564

You need the jQuery .stop() function. Insert it in your command chain before you start a new animation, to interrupt any ongoing animations.

$('#state-slider').hover(function() {
    $(this).stop().animate({ left: 0 }, 500);
}, function() {
    $(this).stop().animate({ left: -270 }, 500);
});

Working jsFiddle =)

Upvotes: 17

Aram Mkrtchyan
Aram Mkrtchyan

Reputation: 2700

there is an example

http://jsfiddle.net/amkrtchyan/TQz5U/1/

and jquery code

$(function() {
    $("#state-slider").hover(function() {
        $(this).stop(true,true).animate({
            left: '0'
        }, 500);
    }, function() {
        $(this).stop(true,true).animate({ left: "-270" }, 500);
    });
});

Upvotes: 0

Rafay
Rafay

Reputation: 31033

$("#state-slider").hover(function() {
  $(this).animate({
    left: '0'
  }, 500);
}, function() {
  $(this).stop(true,true).animate({ left: "-270" }, 500);
});

DEMO

http://api.jquery.com/stop/

Upvotes: 1

Related Questions