Skip to content

Instantly share code, notes, and snippets.

@DenesKellner
Last active September 21, 2020 11:50
Show Gist options
  • Select an option

  • Save DenesKellner/594b5ecc092519772676438e5b679038 to your computer and use it in GitHub Desktop.

Select an option

Save DenesKellner/594b5ecc092519772676438e5b679038 to your computer and use it in GitHub Desktop.
Allows you to easily apply styles based on current Y scroll value. It does this by defining a breakpoint (yes, a single one) and adding/removing a class as you cross that. Implemented with setInterval so it's resource-efficient and won't overwhelm your CPU when scrolling slowly. Has no dependencies, simple as hell.
setTimeout(function() {
var amount = 100; // how many pixels before the miracle happens
var beyondClass = 'beyond-that-point'; // this class will be added
var targetSelector = 'body'; // which element to add the class to
var checkMS = 20; // check scroll position every N milliseconds
var eClass = document.querySelector(targetSelector).classList;
setInterval(function() {
var y = window.scrollY;
var c = beyondClass;
var isBeyond = !!(y>=amount)?1:0;
if(isBeyond==1) if(!eClass.contains(c)) eClass.add(c);
if(isBeyond==0) if( eClass.contains(c)) eClass.remove(c);
},checkMS);
},1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment