JavaScript Scrolling

The next event we are going to look through is scroll: one of the most frequently used events in JavaScript, and not only. With the help of this event, you can react to a page or element scrolling. Here are a few pretty good things to do with it:

  1. Show or hide extra controls or information depending on where the user is in the document.
  2. Load more data, scrolling down up to the end of the page.

A small function showing the current scroll is below:

window.addEventListener('scroll', function () {
  document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
The action is as follows: The current scroll is equal to 0…..px.

The scroll event operates on the window, as well as on scrollable elements. Window-relative coordinates of the whole document can be received as document.documentElement.getBoundingClientRect(), the bottom property can be wondow-relative coordinate of the bottom of the document.The window height can be obtained as document.documentElement.clientHeight:

<!DOCTYPE html>
    <title>Title of the Document</title>
    <h1>Scroll page</h1>
      function scrollBottom() {
        while(true) {
          let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
          // if the user scrolled far enough (<500px to the end)      
          if(windowRelativeBottom > document.documentElement.clientHeight + 500) break;
          document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
      window.addEventListener('scroll', scrollBottom);
      scrollBottom(); // init document

Prevent Scrolling

Let’s learn to make something unscrollable.

It is not possible to prevent scrolling with event.preventDefault() in onscroll listener. The reason is that it triggers only after the scroll has taken place. But, there is another means that can prevent scrolling - it’s using event.preventDefault() on the event, which causes the scroll. For example, the keydown event.preventDefault() for pageUp and pageDown. Adding an event handler to the mentioned events with --onto will stop the scrolling.

There is a variety of ways to start scrolling, but the most reliable one is to use the CSS overflow property.

Practice Your Knowledge

What methods can be used to programmatically scroll the page in JavaScript?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?