user14310667
user14310667

Reputation:

Css animation runs 2 times after first trigger

Im trying to make a navbar that is transparent when youre on the top of the page and when you move down the background for the navigation bar appears but when the animation triggers for the first time it looks like it was triggered twice. How could I fix this?

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>

Upvotes: 0

Views: 161

Answers (1)

user14310667
user14310667

Reputation:

I have fixed it.

$(window).scroll(function(){
    var scroll = $(window).scrollTop();
    if(scroll < 300){
        $('.navbar').css('background', 'transparent');
    } else{
        $('.navbar').css('background', 'white');
    }
});
function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers except IE before #9
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}
body {
    background: linear-gradient(-250deg, #1E3B70, #29539B);
    background-size: 400% 400%;
    margin:0;
    padding:0;
    height:10000px;
}

.navbar {
    margin-top: 0 !important;
    position: fixed !important;
    top:0 !important;
    width:100%;
    height:50px;
    transition:500ms ease;
    background-color: transparent;
}
.navbar.scrolled {
    background:white;
}
    <div id="navbar" class="navbar">TEST</div>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Upvotes: 1

Related Questions