Skip to content

Instantly share code, notes, and snippets.

@techb
Created November 19, 2020 22:05
Show Gist options
  • Save techb/b7e940d7479d6c9090850506f2b3b6f4 to your computer and use it in GitHub Desktop.
Save techb/b7e940d7479d6c9090850506f2b3b6f4 to your computer and use it in GitHub Desktop.
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};
// Get the header
var header = document.getElementById("myHeader");
// Get the offset position of the navbar
var sticky = header.offsetTop;
var stickyBottom = header.offsetBottom;
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
if(window.pageYOffset <= stickyBottom){
header.classList.remove("sticky");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment