SoFunction
Updated on 2025-04-14

Use JavaScript to get page scrolling position

In JavaScript, getting the scroll position of a page usually refers to getting the position of the current page relative to the viewport (browser window), or getting the scroll position of an element relative to the page. Common requirements include listening to user scrolling events, getting scrolling positions when the page is loaded, or implementing smooth scrolling of the page, etc. Below, we will introduce how to obtain horizontal and vertical scrolling positions, and explain in detail based on actual project code.

Get the page scrolling position

  • Get the vertical scroll position (Y-axis)
  • Get the horizontal scroll position (X-axis)

There are usually two ways to get the scrolling position of the page:

  • /: Get the vertical scroll position relative to the top of the browser window.
  • /: Get the horizontal scroll position relative to the left side of the browser window.

Example: Get the scrolling position of the current page

// Get the vertical scroll positionlet verticalScroll =  || ;

// Get the horizontal scroll positionlet horizontalScroll =  || ;

("Vertical scroll position:", verticalScroll);
("Horizontal scroll position:", horizontalScroll);

Get the scroll position of the element

If you want to get the scroll position of a specific element (such as a scroll area), you can use the scrollTop and scrollLeft properties of the element.

  • : Gets the vertical scrolling position of an element relative to its visible area.
  • : Gets the horizontal scrolling position of an element relative to its visible area.

Example: Get the scroll position of a scroll container

Suppose you have a div with a scrollbar, you can use the following code to get the scroll position of that element:

<div  style="width: 200px; height: 200px; overflow: auto;">
  <div style="height: 600px; width: 600px;">Long content</div>
</div>

<script>
  // Get the scroll container  let scrollContainer = ('scrollContainer');

  // Get the scroll position of the container  let containerScrollTop = ;
  let containerScrollLeft = ;

  ("Vertical scroll position of the scroll container:", containerScrollTop);
  ("Horily scrolling position of the scroll container:", containerScrollLeft);
</script>

Dynamically listen for scrolling events

In actual projects, listening to scrolling events of pages or elements is a common requirement. For example, you may want to perform certain actions when the user scrolls the page (e.g., lazy loading, triggering animations, etc.).

Example: Listen to the scroll event of the page

('scroll', function() {
  let verticalScroll =  || ;
  let horizontalScroll =  || ;

  ("Vertical scrolling position of the page:", verticalScroll);
  ("The horizontal scroll position of the page:", horizontalScroll);
});

Use scrolling position to do lazy loading

Suppose you are implementing the function of lazy loading images, and the image will only load when the user scrolls to the location where the image is. Here is an actual code example showing how to load images based on scrolling positions.

Example: Implement lazy loading of pictures based on scrolling positions

<div class="image-container">
  <img data-src="" class="lazy-load" alt="image1" />
  <img data-src="" class="lazy-load" alt="image2" />
  <img data-src="" class="lazy-load" alt="image3" />
</div>

<script>
  function lazyLoadImages() {
    let images = ('.lazy-load');
    let windowHeight = ;
    let windowScrollTop =  || ;

    (function(img) {
      // Get the image relative to the top of the page      let imageTop = ().top + windowScrollTop;

      // If the image enters the viewport, the image is loaded      if (imageTop <= windowScrollTop + windowHeight) {
         = ;  // Set the src attribute of the picture to trigger loading        ('lazy-load');  // Remove lazy loading classes      }
    });
  }

  // Execute when listening for scrolling events and page loading  ('scroll', lazyLoadImages);
  ('load', lazyLoadImages);  // Check it once when the page is loaded</script>

In this example, data-src stores the actual path to the picture, and src is empty or placeholder. When the image enters the viewport, the image is loaded by setting the src property.

Get the scroll position and achieve smooth scrolling

If you need to implement smooth scrolling (such as scrolling to a specific position), you can use or , and smooth scrolling by setting behavior to smooth .

Example: Smoothly scroll to a specific location on the page

<button >Scroll to top</button>

<script>
  // Get button  let scrollButton = ('scrollButton');

  // When clicking the button, scroll smoothly to the top of the page  ('click', function() {
    ({
      top: 0,
      left: 0,
      behavior: 'smooth'  // Set smooth scrolling    });
  });
</script>

Application scenarios in actual projects

  • Implement lazy loading: Load pictures or content according to scrolling positions as mentioned above.
  • Trigger animation effect: Trigger animation or load other content when the user scrolls to a specific location on the page.
  • Custom scrollbars: Customize the scrollbar appearance and get the scroll position for more complex operations.
  • Unlimited scrolling: Load more content as the user scrolls to the bottom of the page.

Example: Infinite scrolling

<div >
  <!-- Initial content -->
</div>

<script>
  let contentContainer = ('contentContainer');

  ('scroll', function() {
    let documentHeight = ;  // Total document height    let windowHeight = ;  // Browser viewport height    let scrollPosition =  || ;  // Current scrolling position
    // If the user scrolls to the bottom of the page    if (scrollPosition + windowHeight >= documentHeight - 100) {
      // Load more content      let newContent = ('div');
       = 'Load more content...';
      (newContent);
    }
  });
</script>

Summarize

Getting and using scrolling positions is a common requirement in front-end development. In JavaScript, you can get the scroll position of the page through , , or get the scroll position of a specific element through , and . Combining technologies such as scroll event monitoring, lazy loading, smooth scrolling and infinite scrolling can improve the user experience and add more complex interactive functions to the page.

The above is the detailed content of using JavaScript to obtain the scroll position of the page. For more information about JavaScript to obtain the scroll position of the page, please pay attention to my other related articles!