Probably you experienced some flashing effect the first time you tried to make a jQuery hover animation without the stop() call. This happens when you hover and take your mouse away quickly without waiting for the animation to finish. This behavior triggers a new animation to start before the previous has finished.
In this article I’m going to present the proper way of making jQuery animation calling the stop() method, avoiding shaking fuzzy effects.
See the first demo where the animation is properly implemented. Try to shake your mouse and the panels won’t go crazy. Try the second demo where I removed the stop() method. Move your mouse quickly above the button a couple times and the animation won’t stop when you leave the button alone.
The HTML code has a button and a couple of panels that we’ll animate
<button id="demo">Hover here!</button> <div class="tab">First Panel</div> <div class="tab">Second Panel</div>
The CSS code adds background colors and sets the unhovered state.
#demo { padding: 5px 20px; font-size: 17px; text-align: center; background-color: #555; color: white; border: solid 1px #666; border-radius: 3px; cursor: pointer; } #demo.hovered { background-color: #000; } .tab { margin-top: 10px; padding: 50px; opacity: 0.5; background-color: #876; }
In the jQuery code we are listening to mouseleave and mouseover events on the button. The events trigger the animations which have callback functions that add a class to the button.
$(document).ready(function () { $('#demo').mouseleave(function(event) { $('.tab').stop().animate({ opacity : '0.5', marginTop: '10px' }, 500, function() { //animation complete $('#demo').removeClass('hovered'); }); }); $('#demo').mouseover(function(event) { $('.tab').stop().animate({ opacity : '1', marginTop: '0px' }, 300, function() { //animation complete $('#demo').addClass('hovered'); }); }); });