None

Stopping jQuery Animation Buildup

February 3, 2010

jQuery can do some cool things. This blog has a mouseover on all of the code blocks so that it expands to fill the width of the screen. Try it:

This allows me to add wide text and the right hand side of it isn't visible until you mouse over the code box.

This can be done using some very simple jQuery code:

$('div.codehilite').hover(function(){
    $(this).animate({width:900},200);
  },function(){
    $(this).animate({width:600},200);
  }
);

However, this code has a problem. If you run your mouse up and down the page quickly, you will trigger all of the animations and they will all run sequentially - they'll carry on after you've stopped moving the mouse.

You can get around this by stopping existing animations before starting a new one. Simply add a call to .stop() before the call to .animate()

$('div.codehilite').hover(function(){
    $(this).stop().animate({width:900},200);
  },function(){
    $(this).stop().animate({width:600},200);
  }
);

References

Tags: jquery events