Anish
Anish

Reputation: 2927

How to stop previous dom element animation in jquery

I am trying to use animation using jquery. When i mouseover the element, it increases the height and when mouseout, returns to original height.

The Problem is when i mouseover from one element to another element, the previous element's animation is still performing. how to stop the animation of the previous element?

Fiddle code:

http://jsfiddle.net/EVZVQ/

Upvotes: 0

Views: 399

Answers (2)

Diode
Diode

Reputation: 25165

This works better.

$('.div_1').mouseover(function(){
    $(this).stop(true).animate({'height':'200px'},200);
});

$('.div_1').mouseout(function(){
    $(this).stop(true).animate({'height':'100px'},200);
});

http://jsfiddle.net/diode/EVZVQ/7/

Upvotes: 0

Jasper
Jasper

Reputation: 76003

Use .stop(): http://api.jquery.com/stop

$('.div_1').mouseover(function(){

    $(this).stop().animate({'height':'200px'},2000);
}).mouseout(function(){

    $(this).stop().animate({'height':'100px'},2000);
});

Notice you can chain the event binding functions instead of selecting .div_1 twice in a row.

Here is a demo: http://jsfiddle.net/EVZVQ/1/

When .stop() is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.

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

Update

You can stop all the divs at once like this (but I'm not sure this is the effect you're looking for):

var $divs = $('.div_1');
$divs.mouseover(function(){

    $divs.stop().filter(this).animate({'height':'200px'},250);
}).mouseout(function(){

    $divs.stop().filter(this).animate({'height':'100px'},250);
});

Here is a demo: http://jsfiddle.net/EVZVQ/2/

Upvotes: 1

Related Questions