If your elements are glitching this is probably because when you change the position to relative
the Y position of the footer increases which tries to send the item back to fixed
which creates a loop. You can avoid this by setting two different cases when scrolling up and down. You don't even need to reference the fixed element, just the footer, and window size.
const footer = document.querySelector('footer');
document.addEventListener("scroll", checkScroll);
let prevY = window.scrollY + window.innerHeight;
function checkScroll() {
let footerTop = getRectTop(footer) + window.scrollY;
let windowBottomY = window.scrollY + window.innerHeight;
if (prevY < windowBottomY) { // Scroll Down
if (windowBottomY > footerTop)
setScrolledToFooter(true) // using React state. Change class or change style in JS.
} else { // Scroll Up
if (windowBottomY <= footerTop)
setScrolledToFooter(false)
}
prevY = windowBottomY
};
function getRectTop(el) {
var rect = el.getBoundingClientRect();
return rect.top;
}
and the position of the element in the style object as follows:
position: scrolledToFooter ? 'relative' : 'fixed'