I am trying to change the background color of body on scroll, but it seems like the scroll event listener isn’t working. here is my code:
"use strict";
// Get all the sections with the class "section"
const sections = document.querySelectorAll(".section");
// Function to update the background color based on the section in view
const updateBackgroundColor = () => {
console.log("updateBackgroundColor called");
const scrollPosition = window.scrollY || window.pageYOffset;
console.log("scrollPosition:", scrollPosition);
sections.forEach((section) => {
const sectionTop = section.getBoundingClientRect().top + scrollPosition;
const sectionBottom = sectionTop + section.offsetHeight;
const backgroundColor = section.getAttribute("data-bg-color");
console.log(
`Section: ${section.classList}, Top: ${sectionTop}, Bottom: ${sectionBottom}, Background Color: ${backgroundColor}`
);
if (scrollPosition >= sectionTop && scrollPosition <= sectionBottom) {
// The section is in view
if (backgroundColor) {
document.body.style.backgroundColor = backgroundColor;
}
}
});
};
// Get the container element
const scroller = document.querySelector(".scroller");
// Add an event listener for the "wheel" event on the container
scroller.addEventListener("wheel", (event) => {
// Prevent the default scroll behavior
event.preventDefault();
// Calculate the scroll direction
const delta = event.deltaY;
// Scroll to the next or previous section based on scroll direction
if (delta > 0) {
scroller.scrollBy({
top: window.innerHeight,
behavior: "smooth",
});
} else if (delta < 0) {
scroller.scrollBy({
top: -window.innerHeight,
behavior: "smooth",
});
}
});
window.addEventListener("scroll", updateBackgroundColor);
I am getting nothing on the console
I am trying to change the background color whenever the user scrolls.
2
Answers
The
wheel
event is not synonymous with thescroll
event.From MDN:
use the
scroll
event and make sure the document is tall enough and with enough content for scrolling to be able to take place.problem is not in EventListener. I think it’s in your function! Can I see your console after scrolling and your HTML code, please.