DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on

Sticky is-stuck web-component

Here's a simple script to watch then a sticky element becomes stuck

class CoSticky extends HTMLElement {
  connectedCallback() {
    this.stickyObserver = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.toggleAttribute('data-sticky', entry.intersectionRatio === 1)
        })
      },
      {
        // root element is required for the rootMargin to work.
        root: this.parentElement,
        // rootMargin allows to trigger the callback before the element is fully out of view.
        rootMargin: '-1px 0px 0px 0px',
        threshold: 1,
      },
    )
    this.stickyObserver.observe(this)
  }

  disconnectedCallback() {
    this.stickyObserver?.disconnect()
  }
}

customElements.define('co-sticky', CoSticky)
Enter fullscreen mode Exit fullscreen mode

Have a nice day!

Top comments (0)