Change Opacity of an element after page scroll

Viewed 651

there is a header in my website, it is transparent when user is at the top of website, but I want to change it's opacity to 50% when the user scrolls until a certain height of the page, HOW DO I DO IT ?

.navbar_outline{
    background-color: yellow;
    border-radius: 50px;
    top: 10px;
    width: 1300px;
    height: 70px;
    position: absolute;
    position: fixed;
    margin-left: 35px;
    opacity: 50%;
}
1 Answers

You can use the window.scrollY feature to add a class to your navbar when the user scrolled enough.

if (window.scrollY>500) {
 var nav = document.getElementById("navbar");
nav.classlist.add("reduced-opacity");
}

and then the css :

.reduced-opacity{
opacity:.5;
}

document.addEventListener('scroll', function(e) {
if (window.scrollY>500) {
 var nav = document.getElementById("nav");
nav.classList.add("reduced-opacity");
}
});
#main{
  height:600vh;
  background:lightblue;
 
}
#nav{
  width:100%;
  height:10vh;
  background:red;
  position:sticky;
  top:10px;

}
.reduced-opacity{
  opacity:.5;
}
<div id="main">
<div id="nav">
  </div>
</div>

Related