scroll-observer

2.1.0 • Public • Published

ScrollObserver

Add a class to an element when a specific scroll threshold has been reached

Installation

npm install --save scroll-observer
yarn add scroll-observer

This is useful if you want to have a sticky nav

Options:

import ScrollObserver from 'scroll-observer'
 
new ScrollObserver(document.querySelector('.nav'), {
    // options, defaults listed
 
    threshold: 1,
    // The scroll threshold you want to use to change state
    // Can also be set to 'this' to dynamically determine the
    // threshold based on the element passed
 
    classNameActive: 'scrollObserver-active',
    // The CSS class applied to the element when `window.scrollY` is reached
 
    classNameInactive: 'scrollObserver-inactive',
    // The CSS class applied to the element when `window.scrollY` not reached
 
});

Examples

// Use the offset of the passed element
new ScrollObserver(document.querySelector('.foo'), {
    threshold: 'this',
});
 
// Set threshold to 50 and change the active class
new ScrollObserver(document.querySelector('.foo'), {
    threshold: 50,
    classNameActive: 'fixToTop',
});

Future development

  • 2nd param could be array so can apply multiple options on the element
  • Is there a need for inactive class?
new ScrollObserver(
    document.querySelector('.foo'),
    [{
        threshold: 'this',
    },
    {
        threshold: 500,
        classNameActive: 'fixToTop',
    }]
);

Testing: [http://jsbin.com/tokuco/edit?js,output]

Made by Z&er ⚡️

Readme

Keywords

Package Sidebar

Install

npm i scroll-observer

Weekly Downloads

0

Version

2.1.0

License

MIT

Unpacked Size

19.5 kB

Total Files

12

Last publish

Collaborators

  • mrmartineau