/*******************************
Author: Bhaumik Mehta
Created on: 02/14/2021
Language: JavaScript
********************************/
//-------------------------- Function starts ------------------------//
/*
1. This reusable function terminates by returning false, if the event target or nodes is undefined/null OR there are no nodes with "not loaded" custom class.
2. Else, it iterates though all the not loaded nodes.
3. This function gets object as an argument.
3. This function can be used for vertical or horizontal scrolling lazy load.
*/
const lazyload = ({ container, nodes, isHorizontal, notLoadedClass="lazy-not-loaded", loadedClass="lazy-loaded" }) => {
if (!container || !nodes || nodes.length === 0) {
return false;
}
/*
1. Convert the images node array to an iterable array and then use map to iterate through each image.
2. If the class contains the not loaded class and the node is in viewport (Checking for class is important to make the "if" block runs only once for each image).
3. Set the source and alt if the node is image and remove the data-src.
4. Remove not loaded class and add loaded class, and return true as the map needs to return something.
*/
Array.from(nodes).map(node => {
if (node.classList.contains(notLoadedClass) && inViewport(node, container, isHorizontal)) {
if (node.tagName === "IMG") {
node.src = node.dataset.src;
node.alt = node.dataset.src;
node.removeAttribute("data-src");
}
node.classList.remove(notLoadedClass);
node.classList.add(loadedClass);
return true;
}
});
};
/*
1. Helper function to calculate and return true/false based on if the node is in the viewport.
2. If it's a horizontal scroll then check if the rect right is greater than zero and if the rect left minus left offset calculation is less than or equal to the container width.
3. For the vertical operation check for the bottom and then if the rect top minus the...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.