Skip to content

Instantly share code, notes, and snippets.

@thisbit
Last active September 27, 2022 17:55
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 thisbit/77abf753b88591cb16600f56f8fb0529 to your computer and use it in GitHub Desktop.
Save thisbit/77abf753b88591cb16600f56f8fb0529 to your computer and use it in GitHub Desktop.
hide show anything on scroll
/* we use variables to that hiding fits perfectly with the nav and aside height/width */
:root {
--nav-height: 90px;
--sidebar-width: 120px;
}
/* menu setup */
body nav {
position: fixed;
top: 0;
left: 0;
right:0;
z-index: 99;
height: var(--nav-height);
transition: 0.25s ease top;
}
/* sidebar setup */
body aside {
position: fixed;
top: 0;
left: 0;
bottom:0;
z-index: 99;
width: var(--sidebar-width);
transition: 0.25s ease left;
}
/* and now hiding and showing */
body.down nav {
top: calc(var(--nav-height) * -1); /* negative margin basicaly */
}
body.down aside {
left: calc(var(--sidebar-width) * -1); /* negative margin basicaly */
}
body.up nav {
top: 0; /* back to zero */
}
body.up aside {
left: 0; /* back to zero */
}
window.addEventListener( 'DOMContentLoaded', ()=> {
const body = document.body,
scrollUp = "up",
scrollDown = "down",
offset = 0;
let lastScroll = window.pageYOffset;
if ( lastScroll > offset ) {
body.classList.add(scrollUp);
}
window.addEventListener('scroll', ()=> {
const currentScroll = window.pageYOffset;
if ( currentScroll <= offset ) {
body.classList.remove(scrollUp);
return;
}
if ( currentScroll > lastScroll && !body.classList.contains(scrollDown) ) {
body.classList.remove(scrollUp);
body.classList.add(scrollDown);
} else if ( currentScroll < lastScroll && !body.classList.contains(scrollUp) ) {
body.classList.remove(scrollDown);
body.classList.add(scrollUp);
}
lastScroll = currentScroll;
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment