Manipulating elements with Javascript page scroll

Asked

Viewed 1,449 times

2

I would like to Show or Hide the menu as per Scroll of the page, I tried to develop in the following way:

  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 am "breaking my head" in this.

OBS: Not want to use Jquery, I need an extremely light page and the only JS of the page will be this, so I’m using JS "pure"

1 answer

4


@Ghabriel you can start by sculpting the scroll event from the window.

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

And inside the event you can check by the value of the variable Scrolly 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";
}

create an example in codepen.io that is in this link http://codepen.io/silviolucenajunior/pen/bErJgm

You can also use pageYOffset which is an alias for Scrolly.

Now you have to look at some things, among them the performance, because the scroll event is fired at each moved pixel, so when moving the scroll bar by 100px the event was fired 100 times. Also need to know if you will listen to the scroll event of the entire window (as I did in the example) or just some specific element.

  • For, exactly what I needed, and I hadn’t really thought about this performance detail, running every pixel moved, I’ll have to do the tests, thank you very much @Darkcreator

  • Not at all @Gabriel Masson.

Browser other questions tagged

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