I'm doing sticky header implementation - I dont want to use position: sticky;
because I dont see good polyfill for it so I'm trying to use IntersectionObserver API instead. The problem is - I dont really like the behaviour it provides as its entries could be emitted with random delay. This solution works fine if you scroll gradually, but if you scroll faster the header goes up and only after delayed response it gets fixed
class and gets positioned with significant jump especially on heavy pages. Any ways to achieve better response or maybe IntersectionObserver is not good for my purposes?
const header = document.querySelector('.header');
const headerPositionNotifier = document.createElement('div');
headerPositionNotifier.classList.add('header-position-notifier')
header.parentNode.insertBefore(headerPositionNotifier, header);
const options = {
threshold: [0]
};
const callback = (entries) => {
entries.forEach(({
intersectionRatio
}) => {
if (intersectionRatio == 0) {
header.classList.add('fixed')
} else {
header.classList.remove('fixed')
}
})
}
const io = new IntersectionObserver(callback, options);
io.observe(headerPositionNotifier);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
text-align: center;
font-family: Arial;
color: white;
letter-spacing: 10px;
}
.banner {
background: orange;
padding: 20px;
}
.parent {
background: mediumvioletred;
position: relative;
}
.header {
background: salmon;
padding: 40px 0;
}
.content {
background: #444;
padding: 40px 0;
height: 2000px;
}
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
}
.header-position-notifier {
height: 1px;
}
<div class="banner">
BANNER
</div>
<div class="parent">
<div class="header">
HEADER
</div>
<div class="content"></div>
</div>