@goboldlyforward/scrollmptious
v2.0.0
Published
Tiny vanilla-JS utility that fires different callbacks based on scroll direction.
Downloads
145
Maintainers
Readme
Scrollmptious
Tiny vanilla-JS utility that fires different callbacks based on scroll direction.
Zero dependencies. ESM. About 80 lines of source. Useful for hide-on-scroll navbars or anything that needs to react when the user reverses direction.
Install
npm install scrollmptiousOr load it as an ES module directly in the browser:
<script type="module">
import { scrollmptious } from 'https://esm.sh/scrollmptious';
scrollmptious(document.querySelector('nav'));
</script>Usage
The default behavior slides the target element off-screen on scroll-down and back on scroll-up — designed for fixed navbars:
import { scrollmptious } from 'scrollmptious';
scrollmptious(document.querySelector('nav'));nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
transition: top 0.25s ease-in-out;
}Wire up your own callbacks instead of the default top-style toggle:
import { Scrollmptious } from 'scrollmptious';
const instance = new Scrollmptious(document.body, {
onDown: ({ scrollTop }) => document.body.classList.add('hide-navs'),
onUp: ({ scrollTop }) => document.body.classList.remove('hide-navs'),
});
// Later:
instance.destroy();Options
| Option | Default | Description |
| -------------- | -------- | --------------------------------------------------------------------------- |
| onUp | null | Called when scrolling up. Receives { direction, scrollTop, instance }. |
| onDown | null | Called when scrolling down past the element's height. |
| delta | 5 | Pixels of movement required before a direction change registers. |
| scrollTarget | window | Element to listen on. Pass a scrollable container to scope detection. |
API
new Scrollmptious(element, options)— returns an instance.scrollmptious(element, options)— convenience wrapper around the constructor.instance.destroy()— removes the scroll listener. Idempotent.
The plugin uses a passive scroll listener and requestAnimationFrame for throttling, so it stays cheap and never blocks the main thread.
Migrating from v1
v1 was a jQuery plugin. v2 is vanilla ESM. The renames:
| v1 (jQuery) | v2 (vanilla) |
| ---------------------------------------- | -------------------------------------------------- |
| $('nav').scrollmptious() | scrollmptious(document.querySelector('nav')) |
| upFunction / downFunction | onUp / onDown |
| this inside callbacks = jQuery element | callbacks receive { direction, scrollTop, instance } |
v1 had a latent bug where custom callbacks never ran (the option name and the property it checked diverged). v2 fixes that.
Development
npm install
npm testTests run against happy-dom via node --test.
License
MIT © Go Boldly Forward
