Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kelsS/331a532d7f6e563d7297c99a64a64517 to your computer and use it in GitHub Desktop.
Save kelsS/331a532d7f6e563d7297c99a64a64517 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>
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.addEventListener('scroll', function() {
scrollpos = window.scrollY;
if (scrollpos >= header_height) { add_class_on_scroll() }
else { remove_class_on_scroll() }
console.log(scrollpos)
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment