UP | HOME

Position Sticky and its events

Position sticky is around for a while, there is still one thing it does not do well, is providing a way to detect whenever an element is sticked or not.

The naive approach would be watching for scroll event, but this is a stupid solution, because it's an expensive operator that will cause jankiness.

A smoother way is using observers, it called IntersectionObserver, the usage is pretty simple:

let observer = new IntersectionObserver((entries, observer) => {
  for (entry of entries) {
    if (entry.isIntersecting) {
      // the element is sticked, do something
    }
  }
});
observer.observe(document.querySelector('your-target'));

Read more at https://developers.google.com/web/updates/2017/09/sticky-headers

Date: 2019-02-12 Tue 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41