How to detect when position: sticky is triggered with JavaScript?

Spread the love

To detect when an element’s position: sticky behavior is triggered using JavaScript, you can utilize the Intersection Observer API.


This API allows you to observe changes in the intersection of a target element with an ancestor element or viewport. For example we write:
HTML:
Sticky Element


JavaScript:
// Target element with sticky positioning
var stickyElement = document.getElementById('stickyElement'); // Intersection Observer options
var options = { root: null, // use the viewport as the root threshold: 1.0 // fully visible
}; // Intersection Observer callback function
var callback = function(entries, observer) { entries.forEach(function(entry) { // Check if the target element is intersecting with the root if (entry.isIntersecting) { console.log('Sticky element is sticky now!'); // Trigger our desired action when the sticky behavior is triggered } else { console.log('Sticky element is no longer sticky!'); // Trigger our desired action when the sticky behavior is no longer active } });
}; // Create an Intersection Observer instance
var observer = new IntersectionObserver(callback, options); // Start observing the target element
observer.observe(stickyElement);

In this example, we create an IntersectionObserver that watches the target element with the position: sticky behavior (stickyElement).
When the threshold is reached, indicating that the target element is fully visible within its containing element (or viewport if root is set to null), the callback function is triggered.
We can then perform our desired actions based on whether the sticky behavior is active or not.