Last active
March 1, 2024 11:02
-
-
Save ohiosveryown/93015ccc1f43437db6169dbfb18196fa 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> | |
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> |
Imma 'na use it. Thank you for sharing.
Thank you for code.
Perfect. Thank you very much.
Have you considered throttling the onscroll event? Very easy with lodash: https://gist.github.com/daltonrooney/f316226fb67648e42b3a484fb91efa3d
window.onscroll = _.throttle( () => {
//do scrolling stuff
}, 100);
Worked perfectly. Thank you tons.
Working fine, Thanks
thanks man! Worked perfectly.
Awesome!!!
thanks a lot!
Where can I set the scroll height to add the class?
thanks!
Deu certo, obrigado
Great stuff, thanks for sharing!
Thank you!
Very useful, @ohiosveryown, thank you!
Thanks a lot!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works really well. Thanks