Last active
July 20, 2022 10:14
-
-
Save mledwards/2c437e6516b3927bcccb4ed3dad2f3bf to your computer and use it in GitHub Desktop.
Tailwind toggle sticky header on scroll
This file contains 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
// Need this to work out which direction the scroll is happening | |
let lastScroll = 0; | |
// Store header component | |
const header = document.querySelector("header"); | |
// Element looks like this: <header class="transition-transform duration-300 fixed w-full"> | |
// On page scroll | |
window.addEventListener("scroll", () => { | |
// Store current page scroll pixels from top | |
const currentScroll = window.pageYOffset; | |
// If we're at the top, or scrolling upwards, show the header | |
if (currentScroll === 0 || lastScroll > currentScroll) { | |
header.classList.remove("-translate-y-full"); | |
// Else hide it | |
} else { | |
header.classList.add("-translate-y-full"); | |
} | |
// Store the scroll position to ccompare on next scroll | |
lastScroll = currentScroll; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment