Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to track the scroll from the top of the page?

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');
  }
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="header">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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading