Search code examples
jqueryoverlayfadeinfadeout

Overlaying a div upon an image on mouseover with fadein fadeout effects


I was creating an overlay upon an image which works when mouseover the image. I use jquery fadein effect for the overlay to appear and fadeout to dissapear. The overlay is a div cointaining a paragraph. The problem is that when i mouseover the paragraph,it is calling the fadeout event again which makes an unwanted flickering.

<html>
<head>
  <script>
      $(document).ready(function(){
         $('.pic').mouseover(function(){
           $(this).next().fadeIn("fast");
         }); 

          $('.overlay').mouseout(function(){
           $(this).fadeOut("fast");
         });       
      });
  </script>
  <style>
    .overlay{ display:none; position:absolute; top:0; width:100%; }
  </style>
</head>
<body>
  <div class="container">
    <img src="xyz.jpg" class="pic" />
    <div class="overlay">
      <p>Hello guys</p>
    </div>
  </div>
</body>

Solution

  • Use instead:

    $('.container').hover(function () {
        $(this).find('.overlay').fadeToggle("fast");
    });