views:

34

answers:

1

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

+1  A: 

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.

Nick Craver
I tried it but it's still vibrates, look : http://jsbin.com/odama3/6/
CIRK
Your second example works but its not good for me because I want a function what I can use for any element :)
CIRK
@CIRK - It's vibrating because `mouseover` and `mouseout` fire when entering a child...you want `.hover()` here which uses `mouseenter` and `mouseleave` which *don't* fire when entering a child. You can still attach it to individual elements if you wish.
Nick Craver
Well ok, it works as I wanted it here so thanks very much! :)
CIRK