Stop jQuery Repeating on Multiple Instances

September 4, 2011 at 7:55 pm By

I’ll often run into this problem in jQuery where if you hover on and off something too many times it’ll repeat the action over and over again. Here’s some example code for an image that you can only partially see, and then which slides down on hover.

	$('#featured-image').hover(function() {
			
		$(this).animate({'height': '200'}, 700);
		
	}, function() {

		$(this).animate({'height': '50'}, 700);
	
	});

If you were to leave it like this then if the user hovered over while the animation was happening, the whole thing would happen again even after they’ve hovered off. To fix this all you gotta do is add the stop() action just before your animation. So now our code looks like this!

	$('#featured-image').hover(function() {
			
		$(this).stop(true, false).animate({'height': '200'}, 700);
		
	}, function() {

		$(this).stop(true, false).animate({'height': '50'}, 700);
	
	});

You can learn more about stop here