Fix a sidebar to the viewport when scrolling. When the header moves out of the viewport, fix the sidebar to the top of the viewport, then revert when the header comes back to view.
<body>
<div class="container">
<main></main>
<aside class="sidebar"></aside>
</div>
</body>
.sidebar {
position: fixed;
}
document.addEventListener("DOMContentLoaded", () => {
const sidebar = document.querySelector('.sidebar')
let options = {
threshold: 0,
};
let callback = (entries, observer) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
sidebar.style.top = 0
}
else {
sidebar.style.top = 'unset';
}
});
};
let observer = new IntersectionObserver(callback, options)
let target = document.querySelector('header')
observer.observe(target)
});