Skip to content

Instantly share code, notes, and snippets.

@shaunwallace
Created November 9, 2017 14:36
Show Gist options
  • Save shaunwallace/0354854923fe49dfe2d64d660ea38f7e to your computer and use it in GitHub Desktop.
Save shaunwallace/0354854923fe49dfe2d64d660ea38f7e to your computer and use it in GitHub Desktop.
Simple demo using the Intersection Observer API
"use strict";
(() => {
const root = document.querySelector("#root");
const docFragment = document.createDocumentFragment();
const arraySize = 100;
const items = Array.from(Array(arraySize).keys());
const options = {
root: null,
rootMargin: "0px",
threshold: (() => {
const thresholdSets = [];
for (let i = 0; i <= 1.0; i += 0.01) {
thresholdSets.push(i);
}
return thresholdSets;
})()
};
const callback = (entries, observer) => {
// for visual threshold purposes set the current threshold value
entries.forEach(entry => {
const currentIntersectionRatio = Math.floor(
entry.intersectionRatio * 100
);
const increaseFactor = 255 / currentIntersectionRatio;
const index = entry.target.getAttribute("data-index");
if (entry.target.childNodes.length) {
entry.target.firstChild.textContent = currentIntersectionRatio;
} else {
const percentage = document.createElement("span");
percentage.textContent = currentIntersectionRatio;
entry.target.appendChild(percentage);
}
entry.target.style.backgroundColor = `rgb(255,
${Math.floor(index * increaseFactor)},
${Math.floor(currentIntersectionRatio - index * increaseFactor)})`;
entry.target.style.opacity = entry.intersectionRatio;
});
};
items.forEach(i => {
const item = document.createElement("div");
const increaseFactor = 255 / arraySize;
item.classList.add("item");
item.setAttribute("data-index", i);
item.style.color = `rgb(0,
${Math.floor(i * 1.5)},
${Math.floor(100 - i * 1.5)})`;
// create observer and pass the reference to the callback that will be fired
// when the set threshold has been crossed bi-directionally
new IntersectionObserver(callback, options).observe(item);
docFragment.appendChild(item);
});
root.appendChild(docFragment);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment