Skip to content

Instantly share code, notes, and snippets.

@JuliaKiselyova
Last active September 26, 2023 10:20
Show Gist options
  • Select an option

  • Save JuliaKiselyova/a8b23a49f60bf4fc0f4d95f534392084 to your computer and use it in GitHub Desktop.

Select an option

Save JuliaKiselyova/a8b23a49f60bf4fc0f4d95f534392084 to your computer and use it in GitHub Desktop.
Make sticky header on scroll up on mobile
/* CSS for Sticky Header on Mobile */
@media screen and (max-width: 768px) {
header {
position: fixed;
top: 0;
width: 100%;
z-index: 999;
transition: top 0.3s ease;
}
}
var lastScrollTop = 0;
var isScrolling = false;
function updateHeaderVisibility() {
var currentScroll = window.pageYOffset || document.documentElement.scrollTop;
var header = document.querySelector("header"); // Selects the first <header> element on the page
if (currentScroll > lastScrollTop) {
// Scrolling down, hide the header
header.style.top = "-100px";
} else {
// Scrolling up, show the header
header.style.top = "0";
}
lastScrollTop = currentScroll;
isScrolling = false;
}
window.addEventListener("scroll", function () {
if (!isScrolling) {
isScrolling = true;
requestAnimationFrame(updateHeaderVisibility);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment