Search code examples
jqueryhovermouseovermouseout

jQuery : How to create a jQuery hover function?


I want to create two functions what fades in and out an element.

This is what I have done so far, but the problem with this is that if you move the mouse while you are in the hovered element it starts vibrating :| How should I make it to not vibrate and work correctly?

<script language="javascript" type="text/javascript">
 function hoverIn(target, speed){
     $(target).fadeIn(speed); 
 }

 function hoverOut(target, speed){
     $(target).fadeOut(speed); 
 }
</script>

LIVE PREVIEW - check out the problem in live


Solution

  • A better way to do this would be using unobtrusive script, the main thing you want is a .stop() call to stop the previous animation, like this:

    <script type="text/javascript">
     function hoverIn(target, speed){
         $(target).stop(true, true).fadeIn(speed); 
     }
    
     function hoverOut(target, speed){
         $(target).stop(true, true).fadeOut(speed); 
     }
    </script>
    

    This is still a problem because mouseover and mouseout fire when entering/leaving a child. However, .hover() uses mouseenter and mouseleave which don't suffer the same problem, and will eliminate your "vibration" problem.

    The unobtrusive version looks like this:

    $(function() {
      $("ul > li").hover(function() {
        $(this).find("ul").stop(true, true).fadeIn('fast');
      }, function() {
        $(this).find("ul").stop(true, true).fadeOut('fast');
      });
    });​
    

    You can see it here, or the even shorter version:

    $(function() {
      $("ul > li").hover(function() {
        $(this).find("ul").stop(true, true).animate({opacity: 'toggle'}, 'fast');
      });
    });​
    

    You can test that here, note that all of these unobtrusive approaches don't use any inline javascript, and work for multiple child menus.