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;

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

  1. 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?

Leave a comment

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.