DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on

1

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)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more