Optimizing Scroll Image Change
February 11, 2025 · AI Conversations
we have above structure make below script so that every one time scroll wll change content
document.addEventListener('DOMContentLoaded', function () {
const scrollContainer = document.querySelector('.post-blog-scroll');
if (scrollContainer) {
const items = scrollContainer.querySelectorAll('.post-scroll-item');
const contentContainer = scrollContainer.querySelector('.post-scroll-content');
const imageContainer = document.querySelector('.post-scroll-image');
let activeIndex = -1; // Track the last active item
contentContainer.addEventListener('scroll', function () {
let closestItemIndex = -1;
let closestDistance = Infinity;
items.forEach((item, index) => {
const itemTop = item.offsetTop – contentContainer.offsetTop;
const distance = Math.abs(contentContainer.scrollTop – itemTop);
if (distance < closestDistance) {
closestDistance = distance;
closestItemIndex = index;
}
});
if (closestItemIndex !== -1 && closestItemIndex !== activeIndex) {
activeIndex = closestItemIndex;
// Reset all items and update the active one
items.forEach(item => item.style.opacity = '0');
items[activeIndex].style.opacity = '1';
// Change image
const imgSrc = items[activeIndex].getAttribute('data-img');
if (imgSrc && imageContainer) {
imageContainer.innerHTML = “;
}
}
});
}
});
1. **Use Intersection Observer:** Instead of manually calculating distances, you can use the `IntersectionObserver` API for better performance.
2. **Ensure Smooth Image Changes:** Avoid flickering by updating images only when necessary.
3. **Prevent Rapid Changes:** Add a slight delay to avoid excessive updates.
Here’s an optimized version using `IntersectionObserver`:
document.addEventListener('DOMContentLoaded', function () {
const scrollContainer = document.querySelector('.post-blog-scroll');
if (scrollContainer) {
const items = scrollContainer.querySelectorAll('.post-scroll-item');
const imageContainer = document.querySelector('.post-scroll-image img');
let observer = new IntersectionObserver(entries => {
let visibleItem = entries.find(entry => entry.isIntersecting);
if (visibleItem) {
items.forEach(item => item.style.opacity = '0'); // Hide all
visibleItem.target.style.opacity = '1'; // Show the active item
// Change image
const imgSrc = visibleItem.target.getAttribute('data-img');
if (imgSrc && imageContainer.src !== imgSrc) {
imageContainer.src = imgSrc;
}
}
}, {
root: scrollContainer.querySelector('.post-scroll-content'),
rootMargin: '0px',
threshold: 0.5 // Change when 50% visible
});
items.forEach(item => observer.observe(item));
}
});
### **Why this is better:**
– **Efficient:** `IntersectionObserver` avoids constant calculations on every scroll event.
– **Smooth Image Updates:** Only updates when necessary, reducing unnecessary DOM changes.
– **Better Performance:** Works efficiently even with many items.
Let me know if you need any tweaks! 🚀