Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented May 3, 2018

This works really well. Thanks

@FelixLapointe

This comment has been minimized.

Copy link

commented Sep 13, 2018

Imma 'na use it. Thank you for sharing.

@antlans

This comment has been minimized.

Copy link

commented Nov 13, 2018

Thank you for code.

@milossumic

This comment has been minimized.

Copy link

commented Nov 29, 2018

Perfect. Thank you very much.

@daltonrooney

This comment has been minimized.

Copy link

commented Dec 6, 2018

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

This comment has been minimized.

Copy link

commented Mar 2, 2019

Worked perfectly. Thank you tons.

@suhailkc

This comment has been minimized.

Copy link

commented Apr 8, 2019

Working fine, Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.