As the user scrolls, I am attempting to animate four headings. First, I create a sticky
positioned div. Then, as the user scrolls over the headings, each one toggles the class .active
sequentially, with the last one remaining visible and the scrolling continuing to the final div.
The issue I'm encountering is that once the .sticky
div becomes sticky, the browser stops detecting further scrolling until the div returns to a non-sticky state.
--- UPDATE
I've made adjustments to the code to transition sequentially, which has improved the functionality. However, I would like the animations to start only when the .sticky
div becomes sticky. When I attempted this, the scroll animation completely stopped working. Additionally, I want to keep all the headings on the same block. If I apply position: absolute
to them, it disrupts the animations as well.
const headings = Array.from(document.querySelectorAll('.animated-text'));
const sticky = document.querySelector('.sticky');
let currentActive = null;
window.addEventListener('scroll', () => {
const viewportHeight = window.innerHeight;
headings.forEach((heading, index) => {
const headingRect = heading.getBoundingClientRect();
if (headingRect.top <= viewportHeight / 2) {
if (currentActive) {
currentActive.classList.remove('active');
}
heading.classList.add('active');
currentActive = heading;
}
});
});
body {
margin: 0
}
section {
position: relative;
}
.sticky {
padding-bottom: 150px;
background: #2d232c;
position: sticky;
top: 0;
overflow: hidden;
height: auto;
color: white;
}
.animated-text {
opacity: 0;
height: 0;
overflow: hidden;
transition: opacity 1s ease, height 1s ease, transform 1s ease;
transform: translateY(0);
}
.animated-text.active {
height: auto;
opacity: 1;
transform: translateY(-20px);
}
.hero, .end {
height: 100px;
background: white;
}
<section class='hero'>
<p>Start</p>
</section>
<section class='sticky'>
<div class='text-animations'>
<h1 class='animated-text active'>Intro</h1>
<h2 class='animated-text'>First</h2>
<h2 class='animated-text'>Second</h2>
<h2 class='animated-text'>Third</h2>
</div>
<p class='intro_content'>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam Lorem ipsum dolor sit...
</p>
</section>
<section class='end'>
<p>End<p>
</section>