jqueryhovermouseleavemouseout

Trigger an un-hover?


In the script below, the first div shows and the second is hidden. But on hover of the first div, it is hidden and the second div shows. Hovering off this second div does not reveal the first div again - I believe because it is hidden and so the "mouseout" function covered by the hover function will not work on a hidden div. I've tried adding separate mouseLeave and mouseout events but am unable to get either to work. Any ideas?

$(document).ready(function(){
  $("#seconddiv").hide();
  $("#firstdiv").hover(function(){
    $("#seconddiv").show();
    $("#firstdiv").hide();
  });
});
.fullwidth {
width: 100%;
padding-top: 25px;
padding-bottom: 25px:
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="firstdiv" class="fullwidth">
<p>First Text</p>
</div>
<div id="seconddiv" class="fullwidth">
<p>Second Text</p>
</div>
</body>
</html>


Solution

  • Hover takes 2 functions. The first in handles in the second handles the out

    To use it in your code example:

      $("#firstdiv").hover(function(){
        $("#seconddiv").show();
        $("#firstdiv").hide();
      },
      function(){
        $("#seconddiv").hide();
        $("#firstdiv").show();  
      }) 
    

    Heres an example https://jsfiddle.net/L8h1gawy/

    See more details here at: https://api.jquery.com/hover/