Last active
November 15, 2019 16:12
-
-
Save umkasanki/9e2fd2b266098cf2c739b5f331265cd0 to your computer and use it in GitHub Desktop.
Animate elements using Intersection Observer API with delay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const drodels = (selector) => { | |
const load = (el) => { | |
if (el.classList.contains('is-dynamic')) { | |
customizeDroedel(el); | |
} | |
el.classList.add('is-loaded'); | |
}; | |
const scrollTop = window.pageYOffset || document.documentElement.scrollTop; | |
const targets = document.querySelectorAll(selector); | |
for (let i = 0; i < targets.length; i++) { | |
let el = targets[i]; | |
// console.log(el.textContent, el.getBoundingClientRect().y); | |
// console.log(elem.getBoundingClientRect().y); | |
if (scrollTop < 100 && el.getBoundingClientRect().y < document.documentElement.clientHeight + scrollTop) { | |
if (el.classList.contains('is-heading')) { | |
load(el); | |
} else { | |
el.classList.add('first-screen'); | |
setTimeout(() => { | |
load(el); | |
el.classList.add(i); | |
}, 1000 + i * 400); | |
} | |
} | |
} | |
const animatedElements = []; | |
let chain = Promise.resolve(); | |
function show(e) { | |
return new Promise((res, rej) => { | |
setTimeout(() => { | |
if (e.classList.contains('is-dynamic')) { | |
customizeDroedel(e); | |
} | |
e.classList.add('is-loaded'); | |
res(); | |
}, 500); | |
}); | |
} | |
const lazyLoad = target => { | |
const io = new IntersectionObserver((entries, observer) => { | |
entries.forEach(entry => { | |
if (entry.isIntersecting) { | |
const el = entry.target; | |
if (!animatedElements.includes(el) && !el.classList.contains('first-screen')) { | |
animatedElements.push(el); | |
chain = chain.then(() => show(el)); | |
} | |
observer.disconnect(); | |
} | |
}); | |
}, {rootMargin: '0% 0% 0%'}); | |
io.observe(target) | |
}; | |
targets.forEach(lazyLoad); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment