Collapse in header with pure javascript

0

I would like to make a header that when scrolling down the scroll bar, it compresses its contents. I have the following script so far.

window.scroll(function() {
    var scroll = window.scrollTop();
    var element = document.getElementById("nav");
    if (scroll >= 140) {
        element.classList.add("rola");
    } else {
        element.classList.remove("rola");;
    }
});

I know that the HTML components are loaded after the window object, so how would I proceed with script ? I do not know how to wait for the component to load.

    
asked by anonymous 05.09.2018 / 20:23

1 answer

1

According to the documentation in the MDN , the window.scroll function receives two parameters, x and y, and not a callback function, as it did. I believe that what you want to do is listen the scroll event and execute the function whenever the page is rolled. To do this, use the scroll event of window :

window.addEventListener('scroll', function (event) {
    ...
});

But this event will be triggered many times when the page is rolled, so be very careful about performance.

    
05.09.2018 / 21:12