Sticky Events – Events for position: sticky;

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 unstuck
  • StickyEvent.STUCK: Fired only when an element becomes stuck
  • StickyEvent.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');
  });
});

Sticky Events – Events for position: sticky;

Elsewhere , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.