Skip to content

Instantly share code, notes, and snippets.

@kobitoDevelopment
Last active December 8, 2022 05:34
Show Gist options
  • Select an option

  • Save kobitoDevelopment/728f303f9f2bff7d5e3c96a603be890f to your computer and use it in GitHub Desktop.

Select an option

Save kobitoDevelopment/728f303f9f2bff7d5e3c96a603be890f to your computer and use it in GitHub Desktop.
<div style="height:300vh;">
<header class="sticky-header"></header>
</div>
let windowHeight = window.innerHeight;
let currentScrollPositionY;
let lastScrollPositionY;
let scrollDirectionY;
const stickHeader = document.querySelector(".sticky-header");
window.addEventListener("scroll", momentumScroll);
function momentumScroll() {
currentScrollPositionY = window.pageYOffset || document.documentElement.scrollTop;
if (currentScrollPositionY > windowHeight) {
if (scrollDirectionY === undefined) {
scrollDirectionY = "bottom";
} else if (scrollDirectionY === lastScrollPositionY) {
scrollDirectionY = scrollDirectionY;
} else if (currentScrollPositionY > lastScrollPositionY) {
scrollDirectionY = "bottom";
} else if (currentScrollPositionY < lastScrollPositionY) {
scrollDirectionY = "top";
}
if (scrollDirectionY === "bottom" && !stickHeader.classList.contains("is-hidden")) {
stickHeader.classList.add("is-hidden");
} else if (scrollDirectionY === "top" && stickHeader.classList.contains("is-hidden")) {
stickHeader.classList.remove("is-hidden");
}
}
lastScrollPositionY = window.pageYOffset || document.documentElement.scrollTop;
}
.sticky-header {
position: fixed;
top: 0;
left: 0;
transform: translateY(0);
width: 100%;
height: 100px;
background-color: blue;
transition: 0.4s;
&.is-hidden {
transform: translateY(-100%);
transition: 0.4s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment