I’m working on creating a special fade-out animation that only happens when a user is scrolling up through a div (it has a separate animation when scrolling down that I don’t want to alter and it happens at a different time so I can’t just toggle classes).
I have the animation working as far as CSS goes, but I’ve stripped down the code to get the trigger working as that’s my last hurdle. I can trigger when I enter the middle div section (as seen in the console log) but the hiccup seems to be where I determine scroll direction.
As you can see in the example, if you scroll back up into the div the console log does appear. However, when I call the handleScroll function and try to log the scroll direction it doesn’t show anything. That’s my last remaining step is just determining scroll direction upon div entry and then if the user is indeed scrolling up just check to see if they’re 50% through the div.
Why aren’t these triggers occurring?
document.addEventListener("DOMContentLoaded", function () {
const section = document.querySelector('.mountain-sect');
// Function to handle intersection changes
function handleIntersection(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Add scroll listener when entering the div
console.log('in section ');
section.addEventListener('scroll', handleScroll);
} else {
// Remove scroll listener when leaving the div
section.removeEventListener('scroll', handleScroll);
}
});
}
// Function to handle scroll event
function handleScroll(event) {
console.log('scrolling');
const target = event.target;
const scrollTop = target.scrollTop;
const scrollDirection = scrollTop > previousScrollTop ? 'down' : 'up';
const scrollHeight = target.scrollHeight;
const clientHeight = target.clientHeight;
const scrollPercentage = (scrollTop / (scrollHeight - clientHeight)) * 100;
console.log(scrollDirection);
if (scrollDirection === 'up' && scrollPercentage < 50) {
window.alert('You are more than 50% through the div while scrolling up.');
}
previousScrollTop = scrollTop;
}
// Create an Intersection Observer instance
const observer = new IntersectionObserver(handleIntersection);
// Observe the target element
observer.observe(section);
});
<div class="container">
<div style="position: relative;"><img src="https://placehold.co/600x400" /></div>
<div class="mountain-sect" style="position: relative;"><img src="https://placehold.co/600x400" /></div>
<div style="position: relative;"><img src="https://placehold.co/600x400" /></div>
</div>