Skip to content

Instantly share code, notes, and snippets.

@nblenke
Created February 26, 2018 15:37
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 nblenke/b322b7eaba56b84ceb6a7198a551ca2b to your computer and use it in GitHub Desktop.
Save nblenke/b322b7eaba56b84ceb6a7198a551ca2b to your computer and use it in GitHub Desktop.
Header collapse on scroll(transition)
<style>
.spacer {
height: 2800px;
}
#test {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
background: red;
transition: top 60ms linear;
}
</style>
<div id="test"></div>
<div class="spacer"></div>
<script>
const handleBarScroll = (selector) => {
const target = document.querySelector(selector)
const { height } = target.getBoundingClientRect()
window.onscroll = () => {
const scrollY = window.scrollY
if (scrollY <= 0) {
target.removeAttribute('style')
return false
}
if (scrollY > height) {
target.style.top = `-${height}px`
return false
}
target.style.top = `-${scrollY}px`
return false
}
}
handleBarScroll('#test')
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment