Skip to content

Instantly share code, notes, and snippets.

@swarad07
Created September 19, 2020 15:16
Show Gist options
  • Save swarad07/fd5674fcc836aca1e092d7b568b5837c to your computer and use it in GitHub Desktop.
Save swarad07/fd5674fcc836aca1e092d7b568b5837c to your computer and use it in GitHub Desktop.
detect-position-sticky
<!-- HTML -->
<div id="nav-container">This will get unsticky scroll </div>
<div id="nav-container-bottom"></div>
<!-- CSS -->
// 1px tracker.
#nav-container-bottom {
min-height: 1px;
min-width: 1px;
}
.nav-container-sticky {
// Separate styles for sticky element go here.
}
<!-- JS -->
// To check when element get's position sticky
var observer = new IntersectionObserver(function(entries) {
// No intersection
if (entries[0].intersectionRatio === 0)
document.querySelector("#nav-container").classList.add("nav-container-sticky");
// Fully intersects
else if (entries[0].intersectionRatio === 1)
document.querySelector("#nav-container").classList.remove("nav-container-sticky");
}, {
threshold: [0, 1]
});
observer.observe(document.querySelector("#nav-container-bottom"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment