Home > Back-end >  How to track the scroll from the top of the page?
How to track the scroll from the top of the page?

Time:09-01

I need to track the scroll from the top of the page in order to add a class to the header. Now my code does not work and the class is not added. How can I solve this problem?

let body = document.querySelector('body');

body.addEventListener('scroll', () => {
  let scrollTop = body.scrollHeight;

  let headerWrapper = document.querySelector('.header');

  if (scrollTop >= 100) {
    headerWrapper.classList.add('hide');
  } else {
    headerWrapper.classList.remove('hide');
  }
});

CodePudding user response:

It looks like you want to use the scrollY property of the window object, rather than working with properties of the body.

window.addEventListener('scroll', () => {
  let headerWrapper = document.querySelector('.header');

  if (window.scrollY >= 100) {
    headerWrapper.classList.add('hide');
  } else {
    headerWrapper.classList.remove('hide');
  }
});
html, body {
  font-size: 14px;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

.header {
  width: 100%;
  background: #CCC;
  font-size: 2em;
  padding: .2em .4em;
  box-sizing: border-box;
  position: sticky;
  top: 0;
}

.hide { display: none; }
<div >Text</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
Text again

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
And more text

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
Also way down here

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
The end

EDIT

The scroll event listener needs to also be on the window, not the body.

  • Related