Search code examples
jqueryhiddenstickyfadeinfadeout

jQuery hover : fading in a hidden div while fading out the "default" one


$(function() {
  $('#wrap').hover(
    function() {
      $('#wrap .image').fadeOut(100, function() {
        $('#wrap .text').fadeIn(100);
      });
    },
    function() {
      $('#wrap .text').fadeOut(100, function() {
        $('#wrap .image').fadeIn(100);
      });
    }
  );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="wrap">
  <div class="image">
    <img src="http://example.com/images/image.png">
  </div>
  <div class="text hide">
    <p>Text text text</p>
  </div>
</div>

I have two divs (one of them hidden with CSS), which I'm fading in and out in alternance inside a common space, on hover.

And I was applying this jQuery code to fade out the image - and fading in the text, on hover

But the problem is that the text div gets sticky and won't fade out - always that the mouse movement is too quick.

Do you know where can it be the solution to this?

I set up an online test : http://paragraphe.org/stickytext/test.html

Thanks for any tip


Solution

  • If your wrapper doesn't have a width AND height on it you may get some strange results as it shrinks once the image element is removed. To see, add a border and fixed height / width around the wrapper. Or at least use the same height for the image and text divs.

    <style type="text/css">
    #wrap { width: 200px; height: 200px; border: 1px solid black; }
    </style>
    

    EDITED

    Removed a code example that wasn't applicable to what you're trying to accomplish.