I have a Bootstrap template that I’m using for a React app. Inside the template, there’s this piece of JS that’s supposed to make the header sticky on scroll. It works in pure HTML, but when I move the header to a React template (which is necessary because React handles i18n), then adding a class this way no longer works. What’s the simplest workaround here?
let selectHeader = select('#header')
if (selectHeader) {
let headerOffset = selectHeader.offsetTop
let nextElement = selectHeader.nextElementSibling
const headerFixed = () => {
if ((headerOffset - window.scrollY) <= 0) {
selectHeader.classList.add('fixed-top')
nextElement.classList.add('scrolled-offset')
} else {
selectHeader.classList.remove('fixed-top')
nextElement.classList.remove('scrolled-offset')
}
}
window.addEventListener('load', headerFixed)
onscroll(document, headerFixed)
}
I’ve tried using jQuery, hasn’t worked either.
2
Answers
This jQuery code selects the header and its sibling element. It calculates the header’s position and adjusts its behavior on scroll. If the user scrolls past the header’s original position, it adds a "fixed-top" class to the header and a "scrolled-offset" class to the sibling element, creating a sticky effect. These changes are triggered on page load and as the user scrolls.
You don’t need JavaScript to make a header sticky. You can use the
position: sticky
CSS rule.A React example.