0

I'm using IntersectionObserver to replace an initially-loaded image with another one as the original image comes into the user's viewport.

I want the image to fade in, as opposed to just straight replacement.

I've tried adding a Jquery loader to the image, but it is not working as I'd like.

function fadeIn(obj) {
  $(obj).fadeIn(1000);
}

document.addEventListener("DOMContentLoaded", function() {
  
  var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));

  if ("IntersectionObserver" in window) {
  
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          let lazyImage = entry.target;
          $(lazyImage).on('load', fadeIn(lazyImage));
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.srcset = lazyImage.dataset.srcset;
          lazyImage.classList.remove("lazy");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

<img 
class="lazy" 
src="https://classroomclipart.com/christmas-tree-with-bright-lights-decoration-animated-clipart-motion-lights-gifts-presents-2.gif"
data-src="https://classroomclipart.com/TN_december-happy-holidays_2.jpg"
data-srcset="https://classroomclipart.com/sm-santa-claus-and-reindeer-singing-christmas-carols-clipart.jpg 2x, https://classroomclipart.com/TN_december-happy-holidays_2.jpg 1x"
width="100"
height="100"
>
Daniel Williams
  • 2,195
  • 7
  • 32
  • 53

1 Answers1

0

Here is a solution that works decently well using jQuery animation: https://jsfiddle.net/ea7fxrL5/

There are two problems in your current code as far as I can tell:

  1. The fadeIn function is actually being called before the image's source is changed to the "TN_december-happy-holidays_2.jpg" image because the load event is triggered immediately on intersection, since the image's "christmas-tree" src has already been loaded.

  2. The image is already at full opacity, so it needs to be hidden before you can fade it in.

Hope this helps!

Neil VanLandingham
  • 1,016
  • 8
  • 15