Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daltonrooney/f316226fb67648e42b3a484fb91efa3d to your computer and use it in GitHub Desktop.
Save daltonrooney/f316226fb67648e42b3a484fb91efa3d to your computer and use it in GitHub Desktop.
Vanilla JS – change/add class based on scroll position.
// https://codepen.io/cmykw/pen/gemxJm
// layout
<nav/>
// style
<style>
body { min-height: 200vh; }
nav {
--ease: all 300ms ease;
position: fixed;
background: pink;
height: 72px;
width: 100%;
opacity: 0.2;
transition: var(--ease);
}
nav.fade-in { opacity: 1; }
</style>
// logic
<script>
import _ from 'lodash';
let scrollpos = window.scrollY
const header = document.querySelector("nav")
const header_height = header.offsetHeight
const add_class_on_scroll = () => header.classList.add("fade-in")
const remove_class_on_scroll = () => header.classList.remove("fade-in")
window.onscroll = _.throttle( () => {
scrollpos = window.scrollY;
if (scrollpos >= header_height) { add_class_on_scroll() }
else { remove_class_on_scroll() }
console.log(scrollpos)
}, 100);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment