Changing background-color while scrolling
(A demo for 'Add Class to Target-Element when Trigger-Element is Scrolled into View')

By Beverley Hooton

Was inspired by a CodePen by @Funsella

No plugins or jQuery

Just a dash of vanilla JavaScript

A class is added to an element when a trigger-element is near the top of the viewport

The trigger can be the same element as the target, or something else entirely

You say how near to top in % or px... and choose the class added

Use the applied class to change CSS styling

More info at the bottom of this page... keep scrolling!

1
2
3
4
5

The End

Add Class to Target-Element when Trigger-Element is Scrolled into View

This page demos a JavaScript function that adds a class (or multiple classes) to a target-element when a trigger-element scrolls to an arbitrary distance from the top of the viewport. The trigger-element can be the same as the target-element, or something else entirely, and the distance can be defined as a positive or negative integer, in % or px, meaning "top" is relative; 100% from top is actually the bottom of the viewport, making this a handy script for simple "element entrance" (just in view) logic.

Works in modern browsers and IE9+ (no CSS fade transitions in IE9).

Please view the source of this page for HTML markup, CSS and JS.

JavaScript Performance Considerations

Because this is a scroll-activated script, the rate at which the function fires has the potential to be very high.

Attaching functions directly to the scroll event is usually a bad idea; Scrolling using a trackpad, scroll wheel, or just by dragging a scrollbar can easily trigger 30 events per second. Scrolling on a smartphone can trigger significantly more.

This script takes performance into consideration by using;

"Debouncing" and "throttling" help improve performance by controlling the effect of potentially expensive JavaScript functions that may otherwise cause a page to become unresponsive when fired repeatedly. Please see the Debouncing and Throttling Explained Through Examples article at CSS Tricks for further information.

Related

More demos and snippets

Did you find this useful? There are more demos and code snippets this way.