A small javascript plugin for adding an event listener for position: sticky; elements,
223 | without the need for an onscroll listener.
Just checkout the titles on this demo page, 226 | their appearance will change when entering or leaving the sticky state.
227 |npm i sticky-event-listener234 |
The setup is fairly easy,
241 | simply create a new instance of the StickyEventListener class for each sticky element
242 | and add an event listener.
import StickyEventListener from 'sticky-event-listener';
245 |
246 | document
247 | .querySelectorAll('.sticker')
248 | .forEach(sticker => {
249 | new StickyEventListener(sticker);
250 | sticker.addEventListener('sticky', event => {
251 | console.log( event.detail.stuck );
252 | });
253 | });
254 |
255 | For most use-cases, 256 | this would be sufficient. 257 | For more options and a detailed information, 258 | checkout the documentation.
259 |The StickyEventListener dispatches an event called sticky when the element enters or leaves the sticky state.
sticker.addEventListener('sticky', event => {
271 | console.log( event.detail.stuck );
272 | });
273 |
274 | Pass options to the class to alter its behavior.
279 | 280 |new StickyEventListener(sticker, {
281 | monitorTop: true,
282 | monitorBottom: false
283 | });
284 |
285 | | Name | 290 |Type | 291 |Default | 292 |Description | 293 |
|---|---|---|---|
| monitorTop | 298 |Boolean | 299 |true |
300 | Whether or not to monitor the element to enter the sticky state on the top. | 301 |
| monitorBottom | 304 |Boolean | 305 |false |
306 | Whether or not to monitor the element to leave the sticky state from the bottom. | 307 |
In some rare use-cases, 317 | you might need to invoke these methods for the plugin to function as intended.
318 | 319 || Name | 324 |Arguments | 325 |Description | 326 |
|---|---|---|
| setStickerTop | 331 |none | 332 |Remeasures the top property of the sticky element and updates the position for the sentinels,
333 | Should be called when the CSS top property for the sticky element changes,
334 | for example when entering or leaving a media query. |
335 |
| setStickerPosition | 338 |none | 339 |Remeasures the position of the sticky element and updates the height for the sentinels, 340 | Should be called when the position of the sticky element (relative to the top of the document) changes, 341 | for example when resizing the window. | 342 |
For example 348 | (but again, only use these methods if the plugin otherwise does not function as intended):
349 | 350 |const instance = new StickyEventListener(sticker);
351 |
352 | // Remeasure the "top" property.
353 | const mql = window.matchMedia('(max-width: 600px)');
354 | mql.addListener(event => {
355 | instance.setStickerTop();
356 | });
357 |
358 | // Remeasure the position.
359 | window.addEventListener('resize', event => {
360 | instance.setStickerPosition();
361 | });
362 |
363 | The Sticky Event Listener plugin is licensed under the CC-BY-4.0 license. 371 |