Is there a way to create a navigation bar that starts off transparent at the top of the page and then becomes opaque as you scroll down? I have tried implementing an animation for this effect, but it seems like the animation triggers twice when it should only trigger once. How can I resolve this issue?
window.onscroll = function () {
var scroll = getScrollTop();
var navbar = document.getElementById('navbar');
if (scroll > 20) {
navbar.classList.remove('onTop');
navbar.classList.add('moved');
}
else{
navbar.classList.remove('moved');
navbar.classList.add('onTop');
}
}
function getScrollTop(){
if(typeof pageYOffset!= 'undefined'){
return pageYOffset;
}
else{
var B= document.body;
var D= document.documentElement;
D= (D.clientHeight)? D: B;
return D.scrollTop;
}
}
body {
background: linear-gradient(215deg, #d55724, #5259e2);
background-size: 400% 400%;
margin:0;
padding:0;
height:1000px;
}
.navbar {
position: fixed;
top:0;
width:100%;
height:50px;
}
.onTop {
position: fixed;
top:0;
width:100%;
height:50px;
animation-iteration-count: 1;
animation: NavBar-onTop .3s;
}
.moved {
background-color: white;
position: fixed;
top:0;
width:100%;
height:50px;
animation-iteration-count: 1;
animation: NavBar-moved .6s;
}
@keyframes NavBar-moved {
from {background-color: rgba(255, 255, 255, 0);}
to {background-color: rgb(255, 255, 255);}
}
@keyframes NavBar-onTop{
from {background-color: rgb(255, 255, 255);}
to {background-color: rgba(255, 255, 255, 0);}
}
<div id="navbar" class="navbar">ExampleNavBar</div>