[Vuejs]-How to detect if an element is sticky or not?

0👍

The IntersectionObserver interface of the Intersection Observer API
provides a way to asynchronously observe changes in the intersection
of a target element with an ancestor element or with a top-level
document’s viewport.

So, A few lines of IntersectionObserver in JavaScript and tricky usage of top: -1px in the CSS could help to achieve this.

The Below code is containing a header and some content. When the page will be scrolled and the header will be stuck at the top, a bottom border will be applied to the header and when the header is not sticky anymore, the border class will be removed.

const el = document.querySelector(".sticky-element")
const observer = new IntersectionObserver( 
  ([e]) => e.target.classList.toggle("threshold-reached", e.intersectionRatio < 1),
  { threshold: [1] }
);

observer.observe(el);
#parent { 
  height: 2000px; 
}

.sticky-element {
  position: sticky;
  top: -1px;
  z-index: 1;
  background: yellow;
}

/* styles for when the header is in sticky mode */
.sticky-element.threshold-reached {
  border-bottom: 1px solid black;
}
<div id="parent">
  
  <br />
  <div class="sticky-element">Header</div>
  <div>Content</div>
  <div>Content</div>
  <div>Content</div>
  <div>Content</div>
  <div>Content</div>
  <div>Content</div>
  <div>Content</div>

</div>

Important- Read more about how this intersection API works.

Leave a comment