Sticky Events is a library that can listen for events on elements that have position: sticky;
applied. It’s an abstraction built on top of the IntersectionObserver
, and provides one with three types of events:
StickyEvent.CHANGE
: Fired when an element becomes stuck or unstuckStickyEvent.STUCK
: Fired only when an element becomes stuckStickyEvent.UNSTUCK
: Fired only when an element becomes unstuck
Usage is quite simple: set up it once, and then add event listeners to the elements:
import { observeStickyEvents, StickyEvent } from "sticky-events";
// Add listeners to all `.sticky-events` elements on the page
observeStickyEvents();
// Events are dispatched on elements with the `.sticky-events` class
const stickies = Array.from(document.querySelectorAll('.sticky-events'));
stickies.forEach((sticky) => {
sticky.addEventListener(StickyEvent.CHANGE, (event) => {
sticky.classList.toggle('bg-dark', event.detail.isSticky);
});
sticky.addEventListener(StickyEvent.STUCK, (event) => {
console.log('stuck');
});
sticky.addEventListener(StickyEvent.UNSTUCK, (event) => {
console.log('unstuck');
});
});
Hi, I know this is an old post, but could you explain a little bit better how to import “sticky-events”?
Even tough npm installs it, it keeps throwing an error when importing (Cannot find module ‘sticky-events’ or its corresponding type declarations).
I’m learing angular and this is becoming a little bit much for me alone to handle. Help?