Sticky Event Listener

A small javascript plugin for adding an event listener for position: sticky; elements, without the need for an onscroll listener.

Just checkout the titles on this demo page, their appearance will change when entering or leaving the sticky state.

Installation Top

npm i sticky-event-listener

Usage Top

The setup is fairly easy, simply create a new instance of the StickyEventListener class for each sticky element and add an event listener.

import StickyEventListener from 'sticky-event-listener';

document
    .querySelectorAll('.sticker')
    .forEach(sticker => {
        new StickyEventListener(sticker);
        sticker.addEventListener('sticky', event => {
            console.log( event.detail.stuck );
        });
    });

For most use-cases, this would be sufficient. For more options and a detailed information, checkout the documentation.

Documentation Top

Events

The StickyEventListener dispatches an event called sticky when the element enters or leaves the sticky state.

sticker.addEventListener('sticky', event => {
    console.log( event.detail.stuck );
});

Options

Pass options to the class to alter its behavior.

new StickyEventListener(sticker, {
    monitorTop: true,
    monitorBottom: false
});
Name Type Default Description
monitorTop Boolean true Whether or not to monitor the element to enter the sticky state on the top.
monitorBottom Boolean false Whether or not to monitor the element to leave the sticky state from the bottom.

Methods

In some rare use-cases, you might need to invoke these methods for the plugin to function as intended.

Name Arguments Description
setStickerTop none Remeasures the top property of the sticky element and updates the position for the sentinels, Should be called when the CSS top property for the sticky element changes, for example when entering or leaving a media query.
setStickerPosition none Remeasures the position of the sticky element and updates the height for the sentinels, Should be called when the position of the sticky element (relative to the top of the document) changes, for example when resizing the window.

For example (but again, only use these methods if the plugin otherwise does not function as intended):

const instance = new StickyEventListener(sticker);

//  Remeasure the "top" property.
const mql = window.matchMedia('(max-width: 600px)');
mql.addListener(event => {
    instance.setStickerTop();
});

//  Remeasure the position.
window.addEventListener('resize', event => {
    instance.setStickerPosition();
});

License Top

The Sticky Event Listener plugin is licensed under the CC-BY-4.0 license.