There is a code. Whether prompt implementation is correct?

The point is that there is a website header that has two classes with different css styles. When scrolling down, it changes its styles, and if it is raised to the top of the page, it gets the original values.

The question is: is the code correctly implemented (does the code work)? Just want to know the opinion.

window.onscroll = function() { document.querySelector('#header'); var el = document.documentElement.scrollTop; if (el > 1) { document.querySelector('#header').classList.add("sticky"); } else { document.querySelector('#header').classList.remove("sticky"); } }; 
  • It is not clear what is the great meaning of the second line of code? - Anton Shchyrov
  • all the rules, only repeated calls wrap the pointer to the DOM object - variable: var header = document.querySelector ('# header'); and work with him already. - Kirill Korushkin
  • @KirillKorushkin, not very much the norm, but there are just no useful recurring calls. - Qwertiy
  • @AntonShchyrov And what exactly is wrong, I'm a new person in js - Alexander Voyna
  • one
    @KirillKorushkin Please try to publish detailed answers containing a specific example of the minimum solution, supplementing them with a link to the source. Answers –references (as well as comments) do not add knowledge to the Runet. - Nicolas Chabanovsky

1 answer 1

 window.onscroll = function() { 

It is better to subscribe through addEventListener .

There is no checking which element scrolls. In this case, this is uncritical, but it can potentially cause unnecessary re-reads and affect performance.

 document.querySelector('#header'); 

Useless code.

 var el = document.documentElement.scrollTop; 

Calling the number (position of the scroll) element should not be.

 if (el > 1) { 

Are 0px and 1px considered as untwisted, and everything else is scrolled?

If this is really what is required, then I would write down >=2 (given that the number is always integer), because otherwise it is not clear without a comment whether this is a mistake or so intended.

  • and how to transfer the initial position of a scroll? to remove var el - Alexander Voyna
  • it is not necessary to remove, but simply rename - Qwertiy