Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juanfernandes/f94aa47dfa45affbbf9ec1fd42446e99 to your computer and use it in GitHub Desktop.
Save juanfernandes/f94aa47dfa45affbbf9ec1fd42446e99 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