Checking scroll position with addEventListener(‘scroll’) causes performance issues. IntersectionObserver is efficient and built-in.
Detect When Element Enters Viewport:
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate-in');
observer.unobserve(entry.target); // Only animate once
}
});
});
// Observe all elements you want to animate
document.querySelectorAll('.fade-in-on-scroll').forEach(el => {
observer.observe(el);
});
With Threshold:
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0.5) { // 50% visible
entry.target.classList.add('visible');
}
});
}, {
threshold: 0.5 // Trigger when 50% visible
});
Lazy Load Images:
const imgObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src; // Load actual image
imgObserver.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
imgObserver.observe(img);
});
No scroll event listeners, ultra-efficient!
