How to detect scroll top in Javascript?

Member

by jennifer , in category: JavaScript , 2 years ago

How to detect scroll top in Javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by libby , 2 years ago

@jennifer you can use document,body.scrollTop and check if 0 to detect scroll top in Javascript, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<html>
<head>
    <title>How to detect scroll top in Javascript?</title>
</head>
<body>
<div style="width:100%; height: 5200px; background-color: yellow"></div>
<script>
    window.onscroll = () => {
        if (document.body.scrollTop === 0) {
            console.log("top");
        }
    };
</script>
</body>
</html>

Member

by napoleon , a year ago

@jennifer 

To detect when a user scrolls to the top of a web page in JavaScript, you can use the scroll event and check the scrollTop property of the document or window object.


Here's an example code snippet:

1
2
3
4
5
6
window.addEventListener('scroll', function() {
  if (document.documentElement.scrollTop == 0) {
    // User has scrolled to the top of the page
    console.log('Scrolled to top!');
  }
});


In this example, we add an event listener to the window object for the scroll event. Inside the event listener, we check if the scrollTop property of the documentElement (which represents the <html> element) is equal to 0. If it is, we assume that the user has scrolled to the top of the page and log a message to the console.


You can also use the window.pageYOffset property instead of document.documentElement.scrollTop to achieve the same result.