How can I make a div disappear when scrolling down 100px from the top?

Viewed 16389

I want to make a div disappear when I scroll down 100px and then reappear when within those 100px again from the top of the browser window. I don't want any animations just want it to vanish and reappear. Can this be done in just HTML and CSS? Can someone provide me the code for this please?

Thanks in advance, Matt

2 Answers

To the best of my knowledge, I don't think that is easily possible. You can embed JavaScript code to your page using the script tag.

This is how I do mine. It's purely JavaScript and does not depend on JQuery.

I'm sure there is a better way, but this works and is intuitive, it's super easy to understand even for beginners.

It adds or removes a class to an element once the user scrolls past 100px from the top. This value of course can be changed.

const main_nav = document.getElementById('main-nav');

window.addEventListener("scroll", () => {
    var y = window.scrollY;
    if (y >= 100){
        main_nav.classList.add('disappear');
        return;
    }
    else{
        main_nav.classList.remove('disappear');
        // note that this is a class defined in your CSS.
    }
});
Related