Skip to main content

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`);
});
note

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:

  1. Inside the scroll event listener, get the current vertical scroll position (window.scrollY).
  2. Use a series of if...else if statements to check if the scroll position is within a certain range.
  3. Set the document.body.style.backgroundColor to 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
}
});
note

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:

  1. Create several full-height sections in your HTML, each with a data-color attribute.
  2. In your scroll listener, loop through each section.
  3. For each section, use getBoundingClientRect().top to find its position relative to the top of the viewport.
  4. 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:

  1. Create a navbar with position: fixed.
  2. Define a CSS class (e.g., .scrolled) that contains the styles for the "scrolled" state.
  3. In your scroll listener, check if the window.scrollY is greater than a certain threshold (e.g., the height of the navbar or just 0).
  4. If it is, add the .scrolled class 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:

  1. Start by adding a scroll event listener to the window object.
  2. Inside the handler, use window.scrollY to get the current scroll position.
  3. For simple distance-based changes, use if/else statements to set the style.backgroundColor of document.body.
  4. For section-based changes, use element.getBoundingClientRect().top to determine which section is in view.
  5. For a fixed navbar, the best practice is to toggle a CSS class based on the scroll position.