Fire An Event When An Element Gets Stuck – Sticky Event Listener

Category: Javascript | October 23, 2019
Author:FrDH
Views Total:147 views
Official Page:Go to website
Last Update:October 23, 2019
License:CC-BY-4.0 license

Preview:

Fire An Event When An Element Gets Stuck – Sticky Event Listener

Description:

A JavaScript library to provide a Sticky Event Listener that fires an event when your element becomes sticky on page scroll.

Works with the CSS position: sticky property. It can be used to animate your sticky navigation bar when the user scrolls down the webpage.

How to use it:

1. Install the package and import the Sticky Event Listener module.

# NPM
$ npm install sticky-event-listener --save
import StickyEventListener from 'sticky-event-listener';

2. Or load the UMD version of the Sticky Event Listener library from the dist folder.

<script src="dist/sticky-event-listener.js"></script>

3. Stick an element to the top using the CSS position: sticky property.

<div class="sticky">
  I will stick to the screen when you reach my scroll position
</div>
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

4. Execute a function when the element gets stuck.

const Sticky = new StickyEventListener(document.querySelectorAll('.sticker'));

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

5. Remeasure the position of the sticky element (e.g. on window resize event)

Sticky.setStickerPosition();

6. Remeasure the top property.

Sticky.setStickerTop();

7. Possible options.

const Sticky = new StickyEventListener(document.querySelectorAll('.sticker'),{
      monitorTop: true,
      monitorBottom: false
});

You Might Be Interested In:


Leave a Reply