jqueryhtmlhovermouseovercross-fade

Crossfade Image with Text using jQuery on Hover


OK So I have an image that to crossfade to another image on hover. I also have descriptive text to crossfade to another text that corresponds to the second image. What I have now, KIND OF wors, the only problem I have with it is that it fades to blank (CSS: Display-none - added so that the second image doesn't pop up on beside first image... I've tried fiddling around the positions, but so far: no dice)

Also, there seems to be spots around it that triggers the function(move your pointer around)...it's almost as if there's some sort of wrapping happening?

Overall, I've tried the show and hide function (as opposed to the fadeIn/fadeOut), and that didn't give me any problems...however, it wasn't giving me the desired effect.

$(".top").mouseenter(function() {
  $(".bottom").fadeIn();
  $(".top").hide();
});

$(".bottom").mouseleave(function() {
  $(".top").fadeIn();
  $(".bottom").hide();
});
.bottom {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="top" src="https://upload.wikimedia.org/wikipedia/commons/a/ac/200px-Fleur-de-Tournesol.PNG">
<img class="bottom" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Orange_-_replace_this_image_female.svg/200px-Orange_-_replace_this_image_female.svg.png">
<p class="top">Top Text</p>
<p class="bottom">Bottom Text</p>


Solution

  • You almost have it. The first thing that makes the transition uncanny is that you call hide() instead of fadeOut(). You probably did this in order to avoid the images' stacking on top of one another momentarily, as you mentioned. Using fadeOut() with absolute positioning is the way to go in this case. Note that I restructured the markup a bit to make it work:

    $(".top").mouseenter(function() {
      $(".bottom").fadeIn();
      $(".top").fadeOut();
    });
    
    $(".bottom").mouseleave(function() {
      $(".top").fadeIn();
      $(".bottom").fadeOut();
    });
    .top, .bottom {
      position: absolute;
      top: 0;
      left: 0;
    }
    
    .bottom {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="top">
      <img src="https://upload.wikimedia.org/wikipedia/commons/a/ac/200px-Fleur-de-Tournesol.PNG">
      <p>Top Text</p>
    </div>
    <div class="bottom">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Orange_-_replace_this_image_female.svg/200px-Orange_-_replace_this_image_female.svg.png">
      <p>Bottom Text</p>
    </div>