.onscroll is only read once

Asked

Viewed 109 times

1

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

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 do I give the scroll on the page, it only reads the action of scroll only once, and always enters the condition else, because begins the scroll in 0

2 answers

2

Try it this way:

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)";
    }
});

1


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

Then I’d be 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>

  • as soon as release give as an answer, it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.