Skip to content

Instantly share code, notes, and snippets.

@mledwards
Last active July 20, 2022 10:14
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 mledwards/2c437e6516b3927bcccb4ed3dad2f3bf to your computer and use it in GitHub Desktop.
Save mledwards/2c437e6516b3927bcccb4ed3dad2f3bf to your computer and use it in GitHub Desktop.
Tailwind toggle sticky header on scroll
// 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