KANAYO AUSTIN KANE KANAYO AUSTIN KANE - 6 months ago 28
Javascript Question

Jquery for hover out of a div

I know this will make a

hoverOver
and
hoverOut
function on a given id:

$(document).ready(function(){
$("#link").hover(
function(){
$("#div").css({"display":"block"});
},
function(){
$("#div").css({"display":"none"});
}
)
});


But I want the
#div
to display as none when the mouse is out of the main div which holds every content with id of
#main
and to also fade out. So I ran this:

$(document).ready(function(){
$("#link").hover(
function(){
$("#div").css({"display":"block"});
};
$("#main").hoverOut(
function(){
$("#div").fadeOut('slow').css({"display":"none"});
};
});


But the code isn't displaying the
#div
as none. Please am still new to jQuery, so I need help from anyone with a better idea. Here is the html for better explanation:

<div id="main">
<a href="javascript:;" id="link">hover here</a>
<div id="div">this is the content</div>
</div>

Answer

You can use mouseenter() and mouseleave()

As per documentation :

hover() method binds handlers for both mouseenter and mouseleave events.

Calling $( selector ).hover( handlerIn, handlerOut ) is shorthand for: $( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

$(document).ready(function() {
  $("#link").mouseenter(function() {
    $("#div").show(); // you can use show() method to show an element
  })
  $('#main').mouseleave(function() {
    $("#div").fadeOut('slow'); // fadeOut will hide the element, no need to hard-code css method 
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
  <a href="javascript:;" id="link">hover here</a>
  <div id="div">this is the content</div>
</div>