3

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>
godblessstrawberry
  • 4,556
  • 2
  • 40
  • 58
  • You could use something like waypoints sticky elements: http://imakewebthings.com/waypoints/shortcuts/sticky-elements/. Has the added benefit of stopping the rest of your content from jumping when the element becomes fixed – Pete Jul 29 '19 at 13:09

1 Answers1

3

If you can't use CSS for this, than you out of luck. The delay just comes from the delay from scrolling events which you can't make go away. As you said, on heavy pages it gets worse. Even on different browser it's more or less worse. I would prefer to combine css position sticky and as fallback the intersection observer.

Brain Foo Long
  • 2,057
  • 23
  • 28