Within a webpage, I have multiple sections. Positioned between the first and second section is a navbar menu. As the user scrolls down and the navbar reaches the top of the page, a function is triggered to fix it in place at the top. While this functionality generally works well by calculating the offset during scrolling, there are instances where an incorrect value is reported, causing the navbar to flicker.
Below is the custom CSS class:
.sticky {
position: fixed;
top: 0;}
and custom JavaScript code:
var checkStickyMenu = function() {
if ($(window).scrollTop() > $("#secondary-nav").offset().top ){
$("#secondary-nav").addClass("sticky")
}
else {
if ($("#secondary-nav").hasClass("sticky")){
$("#secondary-nav").removeClass("sticky");
}}}
$(window).on("scroll", function() {
checkStickyMenu();
console.log("scroll " + "win scroll: " + $(window).scrollTop() + " secnav: " + $("#secondary-nav").offset().top);
})
checkStickyMenu();
The console.log() displays:
custom.js:16 scroll win scroll: 1010.8571 secnav: 377.98209999999995
custom.js:16 scroll win scroll: 1011.4286 secnav: 1011.4286
custom.js:16 scroll win scroll: 1018.8571 secnav: 377.98209999999995
custom.js:16 scroll win scroll: 1031.4286 secnav: 1031.4286
custom.js:16 scroll win scroll: 1053.1428 secnav: 377.9820333984376
custom.js:16 scroll win scroll: 1067.4286 secnav: 1067.4286
custom.js:16 scroll win scroll: 1070.8572 secnav: 377.98213896484367
custom.js:16 scroll win scroll: 1071.4286 secnav: 1071.4286
Observing the log, you can notice that the offset value jumps from the correct value of 377 to values around 10XX, causing the navbar to lose the 'sticky' class.