Anthony_Z
Anthony_Z

Reputation: 725

Swap images on hover with fade

I'm attempting to swap out an image on hover with a fade in / fade out effect. The jQuery below works well because it lazy loads the hover image.

The first example shows a flash of white as the original image is replaced with the new image as it fades in. The second example shows the desired fade in effect by setting the background but somehow loses the fade out effect.

HTML:

<img class="imageHoverLoad lazy" 
  data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" 
  data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />

jQuery:

$('.imageHoverLoad').mouseenter(function() {
   var elem = $(this);
   elem.attr('src', elem.attr('data-hover')).hide().fadeIn(400);
});

$('.imageHoverLoad').mouseleave(function() {
   var elem = $(this);
   elem.attr('src', elem.attr('data-original')).hide().fadeIn(400);
});

Codepen:

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

Upvotes: 0

Views: 1076

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51946

You're replacing the src before your transition, so there's no time to fade out. And you need to specify the fadeOut and wait for the animation promise to resolve before continuing:

$(function() {
  $("img.lazy").lazyload();
});

$('.imageHoverLoad').mouseenter(function() {
  var elem = $(this);
  elem.fadeOut(400).promise().done(function() {
    elem.attr('src', elem.attr('data-hover')).fadeIn(400);
  });
});

$('.imageHoverLoad').mouseleave(function() {
  var elem = $(this);
  elem.fadeOut(400).promise().done(function() {
    elem.attr('src', elem.attr('data-original')).fadeIn(400);
  });
});
.swap-image {
  width: 300px;
  height: 300px;
  margin-bottom: 100px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.js"></script>

<div class="swap-image">
  <img class="imageHoverLoad lazy" data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />
</div>

<div class="swap-image" style="background: url(http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg) no-repeat;">
  <img class="imageHoverLoad lazy" data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />
</div>

Upvotes: 4

Related Questions