Skip to content

Instantly share code, notes, and snippets.

@reidblomquist
Last active March 3, 2017 00:05
Show Gist options
  • Save reidblomquist/3cc7e48e00596f37b138842e68d2e838 to your computer and use it in GitHub Desktop.
Save reidblomquist/3cc7e48e00596f37b138842e68d2e838 to your computer and use it in GitHub Desktop.
Quick Vanilla JS Nav Hideymajig
export default class Navigation {
constructor () {
this.didScroll_ = false
this.lastScrollTop_ = 0
this.delta = 5
this.navbarHeight_ = document.querySelector('.nav').offsetHeight // change to your desired class/selector
window.addEventListener('scroll', () => {
this.didScroll_ = true
})
setInterval(() => { this.checkScroll() }, 250)
}
checkScroll () {
if (this.didScroll_) {
this.hasScrolled()
this.didScroll_ = false
}
}
hasScrolled () {
let lastScrollTop = this.lastScrollTop_
let navbarHeight = this.navbarHeight_
let navEl = document.querySelector('.nav')
let st = document.querySelector('body').scrollTop
// make sure scrolled more than delta
if (Math.abs(lastScrollTop - st) <= this.delta_) {
return
}
// if scrolled down past navbar, add our hide class
// cuz we aint tryna look at the blank padding behind it
if (st > lastScrollTop && st > navbarHeight) {
// scrollin down
navEl.classList.add('nav-up')
} else {
// scrollin up
navEl.classList.remove('nav-up')
}
this.lastScrollTop_ = st
}
}
.nav { // you prob need more stuff like z-index etc but here's the gist to make the hidey part work
position: fixed;
top: 0;
-webkit-transition: top 0.2s ease-in-out;
-ms-transition: top 0.2s ease-in-out;
-o-transition: top 0.2s ease-in-out;
transition: top 0.2s ease-in-out;
&.nav-up {
top: -110px; // whatever your nav height is hurr
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment