So on my website I have a static header at the very top of the site -- it's not fixed to the top of the viewport. However, what I'd like to do is once the user scrolls past the bottom of this div, for a fixed navbar to appear. My code almost works, but only triggers at the top offset of the div, which is the very top of the page. Here's my code:
$("#header-2").hide(); // hide the fixed navbar initially
var topofDiv = $("#header-container").offset().top; //gets offset of header
$(window).scroll(function(){
if($(window).scrollTop() > topofDiv){
$("#header-2").show();
}
else{
$("#header-2").hide();
}
});
Again, I need to trigger showing the fixed navbar once the user scrolls past the bottom of #header-container
, not the top like it does now. Help?
To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element. We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.
jQuery scrollTop() Method The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0.
I think that if you add the height of the div to the top offset you'll get the behaviour you want
$("#header-2").hide(); // hide the fixed navbar initially
var topofDiv = $("#header-container").offset().top; //gets offset of header
var height = $("#header-container").outerHeight(); //gets height of header
$(window).scroll(function(){
if($(window).scrollTop() > (topofDiv + height)){
$("#header-2").show();
}
else{
$("#header-2").hide();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With