Forked from ohiosveryown/change-class-on-scroll.html
Last active
May 17, 2020 16:33
-
-
Save daltonrooney/f316226fb67648e42b3a484fb91efa3d to your computer and use it in GitHub Desktop.
Vanilla JS – change/add class based on scroll position.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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