Last active
September 26, 2023 10:20
-
-
Save JuliaKiselyova/a8b23a49f60bf4fc0f4d95f534392084 to your computer and use it in GitHub Desktop.
Make sticky header on scroll up on mobile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* 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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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