KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2198

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>

Upvotes: 1

Views: 3546

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115282

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>

Upvotes: 2

Alistair Chisholm
Alistair Chisholm

Reputation: 628

Is this what you mean?

  1. Use JS to set initial state as display: none as an inline style
  2. When the mouse enters #link, fade in #div
  3. When the mouse leaves #main, fade out #div

Example:

$(document).ready(function() {
  $("#div").css("display", "none");
  $("#link").on("mouseenter", function() {
    $("#div").fadeIn('slow');
  });
  $("#main").on("mouseleave", function() {
    $("#div").fadeOut('slow');
  });

});

http://codepen.io/anon/pen/oxrRJZ

Upvotes: 0

frnt
frnt

Reputation: 8795

When your cursor enters main div it show #div and when cursor leave main div it hide #div i.e. display from block to back to none.

Jquery,

$(document).ready(function(){
$("#main").mouseenter(function(){
    $("#div").css('display','block');
});
$("#main").mouseleave(function(){
    $("#div").css('display','none');
});
});

Upvotes: 0

Related Questions