Manipulating elements with page scrolling in JavaScript

2

I would like to display or hide the menu according to the scroll of the page, I tried to develop as follows:

  window.scrollTo(function(){
    if (window.scrollTo() > 212) { // se for maior de 212 pixels some o menu
        document.getElementsByTagName("nav").style.display="none";
      } else {
        document.getElementsByTagName("nav").style.display="block";
      }
  });

However it did not work, my intention is to develop a clean and small code, I'm "breaking my head" on it.

No I want to use Jquery , I need an extremely lightweight page and the only JS of the page will be this, so I'm using "pure" JS

    
asked by anonymous 14.01.2016 / 17:16

1 answer

4

@Ghabriel you can start by snooping the window scroll event.

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

And within the event you can check for the value of the scrollY variable and based on it hide or show your div.

if (window.scrollY > 200){
    document.getElementsByTagName("nav").style.display="none";
} else {
    document.getElementsByTagName("nav").style.display="block";
}

I created an example in the codepen.io that is in this link link

You can also use the pageYOffset which is an alias for scrollY.

Now you have to watch for some things, among them the performance, because the scroll event is triggered with each moved pixel, so when moving the scroll bar by 100px the event was triggered 100 times. You also need to know if you are going to type the scroll event of the whole window (as I did in the example) or just some specific element.

    
14.01.2016 / 18:10