How to Change the Background Color on Scroll in JavaScript
Changing the background color as a user scrolls down a page is a popular and engaging visual effect. This can be used to transition between different sections of a site, signal progress, or change the appearance of a fixed element like a navigation bar.
This guide will teach you the core concepts of handling the scroll event in JavaScript. You will learn three practical techniques: changing the body background based on scroll distance, changing it based on which section is in view, and changing the color of a fixed navigation bar once the user scrolls past a certain point.
Core Task: Listening to the scroll Event
The first step for any scroll-based effect is to add an event listener to the window object for the scroll event. This event fires every time the user scrolls the page.
Basic Setup:
window.addEventListener('scroll', function() {
// This function will run every time the user scrolls.
// `window.scrollY` gives us the number of pixels the document is currently scrolled vertically.
const scrollPosition = window.scrollY;
console.log(`Current scroll position: ${scrollPosition}px`);
});
Performance Note: The scroll event can fire very frequently. For complex animations, you should "debounce" or "throttle" this event to avoid performance issues. For simple color changes, it is generally fine.
Solution 1: Change Page Background Based on Scroll Distance
This technique is useful for creating simple, progressive color changes as the user scrolls.
The logic:
- Inside the
scrollevent listener, get the current vertical scroll position (window.scrollY). - Use a series of
if...else ifstatements to check if the scroll position is within a certain range. - Set the
document.body.style.backgroundColorto a different color for each range.
// HTML body must be tall enough to scroll
// e.g., <body style="height: 300vh;">
window.addEventListener('scroll', () => {
const scrollPosition = window.scrollY;
if (scrollPosition < 500) {
document.body.style.backgroundColor = '#ef4444'; // Red
} else if (scrollPosition >= 500 && scrollPosition < 1000) {
document.body.style.backgroundColor = '#3b82f6'; // Blue
} else {
document.body.style.backgroundColor = '#10b981'; // Green
}
});
This will cause the page background to change from red to blue to green as the user scrolls down.
Solution 2: Change Page Background Based on the Current Section
A more advanced technique is to change the background color to match the current full-screen "section" that is in the viewport.
The logic:
- Create several full-height sections in your HTML, each with a
data-colorattribute. - In your
scrolllistener, loop through each section. - For each section, use
getBoundingClientRect().topto find its position relative to the top of the viewport. - If a section's top has scrolled at or above the top of the viewport, update the body's background color to match that section's
data-color.
Consider the following HTML and CSS code:
<section class="fullscreen-section" data-color="coral"></section>
<section class="fullscreen-section" data-color="lightblue"></section>
<section class="fullscreen-section" data-color="lightgreen"></section>
.fullscreen-section {
height: 100vh;
}
body {
transition: background-color 0.5s ease; /* For a smooth transition */
}
and the JavaScript solution:
const sections = document.querySelectorAll('.fullscreen-section');
window.addEventListener('scroll', () => {
let currentSectionColor = '';
sections.forEach(section => {
const sectionTop = section.getBoundingClientRect().top;
// Check if the section is at or above the top of the viewport
if (sectionTop <= 0) {
currentSectionColor = section.getAttribute('data-color');
}
});
// Apply the color of the last section that met the condition
document.body.style.backgroundColor = currentSectionColor;
});
Solution 3: Change a Fixed Navbar's Color on Scroll
This is a very common UI pattern. A transparent navbar at the top of the page becomes opaque or changes color as the user scrolls down.
The logic:
- Create a navbar with
position: fixed. - Define a CSS class (e.g.,
.scrolled) that contains the styles for the "scrolled" state. - In your
scrolllistener, check if thewindow.scrollYis greater than a certain threshold (e.g., the height of the navbar or just0). - If it is, add the
.scrolledclass to the navbar. Otherwise, remove it.
Consider the following HTML and CSS code:
<nav id="navbar">My Website</nav>
#navbar {
position: fixed;
top: 0;
width: 100%;
background-color: transparent;
transition: background-color 0.3s ease;
}
#navbar.scrolled {
background-color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
and the JavaScript solution:
const navbar = document.getElementById('navbar');
window.addEventListener('scroll', () => {
// Check if the user has scrolled more than 0 pixels
if (window.scrollY > 0) {
navbar.classList.add('scrolled');
} else {
navbar.classList.remove('scrolled');
}
});
Conclusion
Handling scroll events is a powerful way to create dynamic and engaging user experiences.
To do it successfully:
- Start by adding a
scrollevent listener to thewindowobject. - Inside the handler, use
window.scrollYto get the current scroll position. - For simple distance-based changes, use
if/elsestatements to set thestyle.backgroundColorofdocument.body. - For section-based changes, use
element.getBoundingClientRect().topto determine which section is in view. - For a fixed navbar, the best practice is to toggle a CSS class based on the scroll position.