Animate elements on scroll
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 19 of 27.
Sometimes we want elements to animate (fade in, slide in, zoom, etc.) when they enter the viewport while scrolling.
This is often done by checking if the element is visible on the screen, then adding a class that triggers a CSS animation or transition.
First, let's create a simple HTML element:
<div class="animate-on-scroll">This element will animate when scrolled into view</div>Next, add CSS for the animation:
.animate-on-scroll {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.5s ease, transform 0.5s ease;
}
.animate-on-scroll.visible {
opacity: 1;
transform: translateY(0);
}Now, let's create a JavaScript function to detect when elements scroll into view. Since we may have multiple elements, we loop through them with forEach and check each element's position relative to the viewport.
function checkScroll() {
const elements = document.querySelectorAll('.animate-on-scroll');
elements.forEach(element => {
// Get element position relative to viewport
const position = element.getBoundingClientRect();
// If element is in viewport
if(position.top < window.innerHeight) {
element.classList.add('visible');
}
});
}
// Run on scroll
window.addEventListener('scroll', checkScroll);
// Run once on page load
checkScroll();When an element with the class animate-on-scroll enters the viewport, the script adds the visible class, triggering the animation.
Challenge
EasyInside the loop, create an if statement.
- The condition should check: if the top position of the element is less than
window.innerHeight - 50. - If the condition is true, use
.classList.add("active")to add theactiveclass to that element.
This way, whenever an element scrolls into view (within 50px from the bottom of the screen), it will smoothly fade in.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Scroll Animation Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Discover the Beauty of Nature</h1>
<p>Scroll down to reveal the magic</p>
</header>
<div class="container">
<div class="fade-in card">
<h2>Mountains</h2>
<p>Standing tall and timeless, mountains remind us of strength and stability.</p>
</div>
<div class="fade-in card">
<h2>Forests</h2>
<p>Forests are the lungs of our planet, offering peace and endless green beauty.</p>
</div>
<div class="fade-in card">
<h2>Rivers</h2>
<p>Calm or powerful, rivers flow endlessly, connecting life along their paths.</p>
</div>
<div class="fade-in card">
<h2>Deserts</h2>
<p>Silent and vast, deserts teach us resilience and the value of every drop of water.</p>
</div>
<div class="fade-in card">
<h2>Oceans</h2>
<p>The oceans cover most of our Earth, a mysterious world full of wonder and life.</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.