<button id="load-button">Load items</button>
<div id="item-list"></div>
.item {
width: 20rem;
height: 10rem;
background-color: #555;
margin: 1rem;
display: inline-block;
}
/**
* This is NOT meant to be an example of how to do
* animation i javascript.
* I did the animations quick and dirty only to
* show how to use the prefers-reduced-motion media-query
* in javascript.
*/
const loadButton = document.getElementById("load-button");
const itemList = document.getElementById("item-list");
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
let prefersReducedMotion = mediaQuery.matches;
mediaQuery.addEventListener("change", () => {
prefersReducedMotion = mediaQuery.matches;
});
loadButton.addEventListener("click", () => {
itemList.innerHTML = "";
setTimeout(loadItems, 300);
});
const loadItems = () => {
for (let i = 0; i < 10; i++) {
var newNode = document.createElement("div");
newNode.classList.add("item");
itemList.appendChild(newNode);
if (!prefersReducedMotion) {
newNode.style.opacity = 0;
animateItem(newNode, i * 100);
}
}
};
const animateItem = (item, delay) => {
let opacity = parseFloat(item.style.opacity);
if (opacity < 1) {
opacity += 0.05;
setTimeout(() => {
animateItem(item);
}, delay || 10);
}
item.style.opacity = opacity;
};
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.