Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidverhage/9773164c31626f3f09b01ddac5443872 to your computer and use it in GitHub Desktop.
Save davidverhage/9773164c31626f3f09b01ddac5443872 to your computer and use it in GitHub Desktop.
Vanilla JS – change/add class based on scroll position.
<div id="header"></div>
<style>
#header {
position: fixed;
background: pink;
height: 72px;
width: 100%;
opacity: 0.2;
transition: all 300ms ease;
}
#header.fade-in {
opacity: 1;
}
</style>
<script>
var scrollpos = window.scrollY;
var header = document.getElementById("header");
function add_class_on_scroll() {
header.classList.add("fade-in");
}
function remove_class_on_scroll() {
header.classList.remove("fade-in");
}
window.addEventListener('scroll', function(){
scrollpos = window.scrollY;
if(scrollpos > 60){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
console.log(scrollpos);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment