Skip to content

Instantly share code, notes, and snippets.

@adampatterson
Created May 19, 2023 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adampatterson/a66c090d787c3948f2670369e38b6f79 to your computer and use it in GitHub Desktop.
Save adampatterson/a66c090d787c3948f2670369e38b6f79 to your computer and use it in GitHub Desktop.
Show hide navigation
<style>
.hide-header-mobile,
.hide-header {
width: 100%;
position: fixed;
transition: all .3s ease!important;
}
.hide-header-mobile {
display: none; /* Initially hide mobile menu */
}
@media (max-width: 768px) {
.hide-header-mobile {
display: block; /* Display mobile menu below 768px */
}
.hide-header {
display: none; /* Hide desktop menu below 768px */
}
}
</style>
<script>
var prevScrollPos = window.pageYOffset;
var hideHeaderMobile = document.getElementById("hide-header-mobile");
var hideHeader = document.getElementById("hide-header");
var isMobile = window.innerWidth <= 768;
function hideMenuOnScroll() {
// Don't allow Apple tackpads or magic mice to over scroll the top of the page.
var currentScrollPos = Math.max(window.pageYOffset, 0);
if (currentScrollPos > prevScrollPos) {
// Scrolling down
if (isMobile) {
hideHeaderMobile.style.transform = "translateY(-100%)";
} else {
hideHeader.style.transform = "translateY(-100%)";
}
} else {
// Scrolling up
if (isMobile) {
hideHeaderMobile.style.transform = "translateY(0)";
} else {
hideHeader.style.transform = "translateY(0)";
}
}
prevScrollPos = currentScrollPos;
}
window.addEventListener("scroll", hideMenuOnScroll);
window.addEventListener("resize", function() {
isMobile = window.innerWidth <= 768;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment