Sticky header using intersection observer
by ygongdev
HTML
<nav id="header" class="collapsible-header">
Header
</nav>
<main id="content">
<div id="sentinel"></div>
<section class="my-section">
Section 1
</section>
<section class="my-section">
Section 2
</section>
<section class="my-section">
Section 3
</section>
</main>
CSS
body {
padding: 0;
margin: 0;
}
.hide {
display: none;
}
.show {
display: block;
}
.collapsible-header {
position: sticky;
background-color: cyan;
width: 100%;
top: 0;
}
#content {
padding: 20px;
}
.my-section {
background-color: gray;
height: 500px;
margin-bottom: 20px;
}
#sentinel {
height: 1px;
background-color: red;
}
JavaScript
function sentinelIO() {
const sentinel = document.getElementById("sentinel");
const header = document.getElementById("header");
const options = {
root: document,
rootMargin: "0px",
threshold: 0,
}
const callback = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log("entering")
header.classList.remove('show');
header.classList.add('hide');
} else {
console.log("leaving");
header.classList.remove('hide');
header.classList.add('show');
}
});
}
observer = new IntersectionObserver(callback, options);
observer.observe(sentinel);
}
sentinelIO();