Skip to content

Instantly share code, notes, and snippets.

@nblenke
Created February 26, 2018 15:38
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/3f4f64e951d21bba5d6206743a084e7f to your computer and use it in GitHub Desktop.
Save nblenke/3f4f64e951d21bba5d6206743a084e7f to your computer and use it in GitHub Desktop.
Header collapse on scroll(translate3d)
<style>
.spacer {
height: 2800px;
}
#test {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
background: red;
transition: transform 200ms linear;
backface-visibility: hidden;
perspective: 1000;
}
</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
}
if (scrollY > height) {
target.style.transform = `translate3d(0, -${height}px, 0)`
return
}
target.style.transform = `translate3d(0, -${scrollY}px, 0)`
return false
}
}
handleBarScroll('#test')
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment