Skip to content

Instantly share code, notes, and snippets.

@ohiosveryown
Last active March 1, 2024 11:02
Show Gist options
  • Star 75 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save ohiosveryown/93015ccc1f43437db6169dbfb18196fa to your computer and use it in GitHub Desktop.
Save ohiosveryown/93015ccc1f43437db6169dbfb18196fa 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>
@Paul-Morris
Copy link

This works really well. Thanks

@FelixLapointe
Copy link

Imma 'na use it. Thank you for sharing.

@antvch
Copy link

antvch commented Nov 13, 2018

Thank you for code.

@milossumic
Copy link

Perfect. Thank you very much.

@daltonrooney
Copy link

Have you considered throttling the onscroll event? Very easy with lodash: https://gist.github.com/daltonrooney/f316226fb67648e42b3a484fb91efa3d

window.onscroll = _.throttle( () => {
    //do scrolling stuff
  }, 100);

@JFarand
Copy link

JFarand commented Mar 2, 2019

Worked perfectly. Thank you tons.

@suhailkc
Copy link

suhailkc commented Apr 8, 2019

Working fine, Thanks

@priyanshupandey1999
Copy link

thanks man! Worked perfectly.

@chris74er
Copy link

Awesome!!!

@CeilloNoll
Copy link

thanks a lot!

@hedanielld
Copy link

Where can I set the scroll height to add the class?

@sebdur
Copy link

sebdur commented Dec 14, 2020

thanks!

@felipegenuino
Copy link

Deu certo, obrigado

@juanmi-sansinenea
Copy link

Great stuff, thanks for sharing!

@leetheresa
Copy link

Thank you!

@tomatillodesign
Copy link

Very useful, @ohiosveryown, thank you!

@Stml-St
Copy link

Stml-St commented Dec 3, 2022

Thanks a lot!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment