Header collapse with pure javascript

Asked

Viewed 36 times

0

I would like to make a header that when scrolling down, it compresses its content. 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 the components HTML are loaded after the object window, then how would you proceed with the script? I don’t know how to wait for the component to load.

  • You can use window.onscroll = function() { /* Code Here */ }

1 answer

1


As documented in the MDN, the function window.scroll receives two parameters, x and y, not a function callback, as you did. I believe what you want to do is listen to the event of scroll and execute the function always the page is rolled. For this, use the event scroll of window:

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

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

Browser other questions tagged

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