Cobolt
Cobolt

Reputation: 952

Using jQuery to make a div fadein on mouseover of a link

what I'm trying to do should be simple but it's complicated by the way the html is structured which I can't change. I basically need what stackoverflow has in the header when mouseover of your account happens. A little menu fades in and out again when the mouse leaves.

HTML

  <div id="top-links">
    <a id="my_link">Link</a>
    <div id="my_mouseover">
      content
    </div>
  </div>

Javascript

 $jQ('#my_link').mouseenter(function(){
  $jQ('#my_mouseover').fadeIn(200);
  $jQ('#my_mouseover').mouseleave(function(){
      $jQ('#my_mouseover').fadeOut();
  });
  $jQ('#my_link').mouseleave(function(){
      $jQ('#customer_mouseover').fadeOut();
  });
});

My problem is that the div fades back in and out when i move my mouse between the <a> and <div>. Is there some way to say:

$jQ('#my_mouseover').mouseleave(function(){
      //there's no such thing as mouseIsOver
  if(!$jQ('#my_link').mouseIsOver()){
    $jQ('#customer_mouseover').fadeOut();
  }    
});

Does anyone know how to do this? I'm not able of finding what I need on google.

Upvotes: 1

Views: 736

Answers (4)

Cobolt
Cobolt

Reputation: 952

I had problems when adding additional links with the approach Pete shared with me, eventually this is what I did:

  $('#top-links').mouseenter(function(){
 $('#my_link').mouseenter(function(){
     //fade everything else out
     $('#my_mouseover2').fadeOut();
     $('#my_mouseover').fadeIn(200);
 });
 $('#my_link2').mouseenter(function(){
     $('#my_mouseover').fadeOut();
     $('#my_mouseover2').fadeIn(200);
 });
});
 $('#top-links').mouseleave(function(){

$('#my_mouseover').fadeOut(200);
$('#my_mouseover2').fadeOut(200);
});

Upvotes: 0

som
som

Reputation: 4656

$('#top-links').on({
    mouseenter : function() {
        $('#my_mouseover').fadeIn(200);
    },
    mouseleave : function(){
        $('#my_mouseover').fadeOut(200);
    }
});

Upvotes: 0

bipen
bipen

Reputation: 36531

add the mouseenter and leave event to you parent container.. this will get the mouseover and mouseleave event for its shild element (<a> and <div>) too

$('#top-links').hover(function(){
  $('#my_mouseover').fadeIn(200);
},function(){
  $('#my_mouseover').fadeOut(200);
});

NOTE: you can use .hover() instead of creating two sepearte function for each event

Upvotes: 0

Pete
Pete

Reputation: 58422

You could put the mouseenter and mouseleave on the top-links div:

$('#top-links').mouseenter(function(){
  $('#my_mouseover').fadeIn(200);
});
$('#top-links').mouseleave(function(){
  $('#my_mouseover').fadeOut(200);
});

http://jsfiddle.net/KJE7x/

Upvotes: 1

Related Questions