Responsive Fading Image Grid With Lazy Load

Category: Javascript , Layout | February 9, 2018
Author: Dominic Magnifico
Views Total: 929
Official Page: Go to website
Last Update: February 9, 2018
License: MIT

Preview:

Responsive Fading Image Grid With Lazy Load

Description:

A responsive fading image grid that uses Intersection Observer to lazy load images as they scrolled into view.

How to use it:

Add placeholder images to the grid.

<div class="grid-container">
  <div class="grid-item"><img src="placeholder.jpg" /></div>
  <div class="grid-item"><img src="placeholder.jpg" /></div>
  <div class="grid-item"><img src="placeholder.jpg" /></div>
  <div class="grid-item"><img src="placeholder.jpg" /></div>
  <div class="grid-item"><img src="placeholder.jpg" /></div>
  ...
</div>

The necessary CSS/CSS3 styles for the image grid.

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  grid-auto-rows: minmax(270px, 1fr);
  max-width: 1280px;
  margin: 0 auto;
}

.grid-row,
.grid-item {
  display: block;
  overflow: hidden;
}

.grid-item img {
  -o-object-fit: cover;
     object-fit: cover;
  -o-object-position: center;
     object-position: center;
  width: 100%;
  height: 100%;
}

.grid-item {
  -webkit-transform: translateY(-10%);
  transform: translateY(-10%);
  opacity: 0;
  -webkit-transition: 600ms opacity cubic-bezier(0.55, 0.055, 0.675, 0.19) 300ms, 600ms -webkit-transform cubic-bezier(0.55, 0.055, 0.675, 0.19);
  transition: 600ms opacity cubic-bezier(0.55, 0.055, 0.675, 0.19) 300ms, 600ms -webkit-transform cubic-bezier(0.55, 0.055, 0.675, 0.19);
  transition: 600ms transform cubic-bezier(0.55, 0.055, 0.675, 0.19), 600ms opacity cubic-bezier(0.55, 0.055, 0.675, 0.19) 300ms;
  transition: 600ms transform cubic-bezier(0.55, 0.055, 0.675, 0.19), 600ms opacity cubic-bezier(0.55, 0.055, 0.675, 0.19) 300ms, 600ms -webkit-transform cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.grid-item.inview {
  -webkit-transform: translateY(0);
  transform: translateY(0);
  opacity: 1;
}

The main JavaScript to lazy load actual images to the grid.

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
      const rand = Math.floor(Math.random() * 30);
      if (entry.isIntersecting === true) {
          const img = entry.target.querySelector("img");
          entry.target.classList.add("inview");
          img.src = `https://source.unsplash.com/random/960x540/?${rand}`;
      } else {
          entry.target.classList.remove("inview");
      }
  });
});
const items = document.querySelectorAll(".grid-item");

items.forEach((item, index) => {
  observer.observe(item, index);
});

You Might Be Interested In:

Leave a Reply