.onscroll is read only once

1

I'm having some problems with a .onscroll function:

window.onscroll=function(){
    if(document.documentElement.scrollTop>5){
        menuPrincipal.style.backgroundColor = "rgba(0,0,0,1)";
    }else{
        menuPrincipal.style.backgroundColor = "rgba(0,0,0,.4)";
    }
}

In this case, when I give scroll to the page, it only reads the action of scroll once, and always enters the condition else , since scroll starts at 0

    
asked by anonymous 28.03.2017 / 14:46

2 answers

1

I think you want to use document.body and not documentElement .

In this case it would look like this:

var menuPrincipal = document.getElementById('menuPrincipal');
window.onscroll = function() {
    console.log(document.body.scrollTop);
    if (document.body.scrollTop > 5) {
        menuPrincipal.style.backgroundColor = "rgba(0,0,0,1)";
    } else {
        menuPrincipal.style.backgroundColor = "rgba(0,0,0,.4)";
    }
}
#menuPrincipal {
    height: 2000px;
    background: #eef;
    padding: 20px;
}
<div id="menuPrincipal"></div>
    
28.03.2017 / 14:51
2

Try this:

window.addEventListener('scroll', function(e) {
    if(document.documentElement.scrollTop>5){
        menuPrincipal.style.backgroundColor = "rgba(0,0,0,1)";
    }else{
        menuPrincipal.style.backgroundColor = "rgba(0,0,0,.4)";
    }
});
    
28.03.2017 / 15:03