ImagesLesson 80Free preview
Change Bg on Scroll
This lesson is part of How To · All levels
Summary
Change background on scroll causes a header or element to change color as a page rolls past a certain boundary. JavaScript reads the scroll position, then adds or removes the CSS class. The transition to the background color makes the change feel subtle and not surprising.
Key points
- Window.scrollY shows the vertical scroll distance in pixels.
- EventListener scrolls run whenever the roll position changes.
- With the condition of determining the class based on the threshold.
- The {passive: true} option helps the listener scroll performance.
- Call the function once when the page is loaded to get the initial status correct.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.