Event to detect when position:sticky is triggered Event to detect when position:sticky is triggered javascript javascript

Event to detect when position:sticky is triggered


Demo with IntersectionObserver (use a trick):

// get the sticky elementconst stickyElm = document.querySelector('header')const observer = new IntersectionObserver(   ([e]) => e.target.classList.toggle('isSticky', e.intersectionRatio < 1),  {threshold: [1]});observer.observe(stickyElm)
body{ height: 200vh; font:20px Arial; }section{  background: lightblue;  padding: 2em 1em;}header{  position: sticky;  top: -1px;                       /* ➜ the trick */  padding: 1em;  padding-top: calc(1em + 1px);    /* ➜ compensate for the trick */  background: salmon;  transition: .1s;}/* styles for when the header is in sticky mode */header.isSticky{  font-size: .8em;  opacity: .5;}
<section>Space</section><header>Sticky Header</header>