Last active
May 9, 2024 16:56
-
-
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> |
Great stuff, thanks for sharing!
Thank you!
Very useful, @ohiosveryown, thank you!
Thanks a lot!!
Works great! Thanks a lot!
What kind of license is this under? Do I have to mention something anywhere, when using the javascript part? I'm new to github/gist.
Works great! Thanks a lot!
What kind of license is this under? Do I have to mention something anywhere, when using the javascript part? I'm new to github/gist.
Feel free to use wherever and however you'd like. All open source here 👍.
Works great! Thanks a lot!
What kind of license is this under? Do I have to mention something anywhere, when using the javascript part? I'm new to github/gist.Feel free to use wherever and however you'd like. All open source here 👍.
Awesome! Thanks again!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Deu certo, obrigado