SoFunction
Updated on 2025-04-09

Detailed explanation of JavaScript page scrolling event example

In modern web development, page scroll event is an important interactive tool that allows developers to trigger a series of functions based on the user's scrolling behavior, thereby enhancing the user experience. This article will introduce in detail the basic concepts, application scenarios and some optimization techniques of page scrolling events to help developers flexibly use scrolling events in actual projects.

1. Overview of page scrolling events

1. What is a page scroll event?

A page scrolling event is an event that the browser triggers when the user scrolls the page. Whether it is through the mouse scroll wheel, arrow keys on the keyboard, or the sliding action of the touch device, as long as the page content scrolls, it will be triggered.scrollevent.

JavaScript provides an easy way to listen for this event, throughwindowor a specific DOM elementaddEventListenerMethod, we can react to scrolling behavior.

('scroll', () => {
  ('The page is scrolling');
});

2. Commonly used scroll event targets

Scrolling events can be bound to the following common targets:

  • window: Scrolling the entire window, such as scrolling up and down for a long page.
  • Specific elements: For example, withoverflowA style container that fires when the contents in it are scrolled.
const container = ('scrollable');
('scroll', () => {
  ('Container is scrolling');
});

2. Basic usage of page scrolling events

1. Detect scrolling position

In actual development, one of the common needs is to get how far the user has scrolled. This can be done throughorGet the scroll position of the page in the vertical direction.

('scroll', () => {
  const scrollTop =  || ;
  (`Current scrolling position:${scrollTop}`);
});

2. Scroll to the bottom or top detection

Detecting whether the user scrolls to the bottom of the page is also a common requirement, especially when implementing the unlimited loading function. By comparisonscrollTopand the total height of the page content, you can determine whether it reaches the bottom.

('scroll', () => {
  const { scrollTop, scrollHeight, clientHeight } = ;
  if (scrollTop + clientHeight >= scrollHeight) {
    ('Scrolled to the bottom');
  }
});

Similarly, it can also be done byscrollTop === 0To determine whether the user scrolls to the top of the page.

3. Application scenarios of page scrolling events

1. Implement the Back to Top button

The Back to Top button is a common interactive element in web pages. When the user scrolls to a certain distance, the button appears, and the page will scroll smoothly back to the top after clicking. passscrollEvents monitor the user's scrolling distance, and this function can be easily achieved by displaying and hiding the CSS control buttons.

const backToTopButton = ('backToTop');

('scroll', () => {
  if ( > 300) {
     = 'block';
  } else {
     = 'none';
  }
});

('click', () => {
  ({ top: 0, behavior: 'smooth' });
});

2. Unlimited loading

In long pages (such as social media or news sites), new content is often loaded with infinite scrolling. After scrolling to the bottom, new data is automatically requested and page content is inserted to reduce user clicks and improve the experience.

('scroll', () => {
  const { scrollTop, scrollHeight, clientHeight } = ;
  if (scrollTop + clientHeight >= scrollHeight) {
    loadMoreContent(); // Functions that load more content  }
});

3. Page animation effect

Scroll animation effects are becoming more and more popular in modern web design. By monitoringscrollEvents can trigger different animations when the user scrolls the page. For example, when certain elements enter the visible area, a gradient appears or moves.

('scroll', () => {
  const elements = ('.animate');
  (el => {
    const rect = ();
    if ( < ) {
      ('visible');
    }
  });
});

4. Optimize rolling event performance

Scrolling events are high-frequency trigger events that may be triggered dozens or even hundreds of times per second. Therefore, it is important to optimize the handling of rolling events in performance-sensitive projects. Common optimization methods include:

1. Use requestAnimationFrame

requestAnimationFrameCode can be executed before the next frame of the browser renders, thereby avoiding unnecessary redrawing and rearrangement and improving performance.

let ticking = false;

('scroll', () =&gt; {
  if (!ticking) {
    (() =&gt; {
      handleScroll(); // Scrolling processing function      ticking = false;
    });
    ticking = true;
  }
});

2. Use throttling or anti-shaking

When scrolling events are frequently triggered, the number of executions of the handler may be too frequent, resulting in performance problems. Throttle and anti-shake are two common optimization solutions.

  • Throttle: Ensure that the function is executed only once within the specified time.
  • Anti-shake: Make sure the function is executed after a period of time, and if the event fires again during this period, it will be re-timed.
function throttle(fn, limit) {
  let inThrottle;
  return function() {
    if (!inThrottle) {
      (this, arguments);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

('scroll', throttle(handleScroll, 100));

5. Frequently Asked Questions and Precautions

1. The trigger frequency of scroll events is too high

becausescrollEvent triggering frequency is high, so when dealing with complex logic, it is easy to cause performance problems, especially on mobile devices. Try to avoid performing a large number of DOM operations every time you roll, and use throttling or anti-shake technology rationally.

2. Compatibility issues

In some old browsers,scrollThe performance of events may be inconsistent, especially between different devices. To ensure good compatibility, developers should conduct adequate testing in various devices and browsers to avoid scrolling events affecting the user experience.

3. Mobile rolling performance

The performance of rolling event processing on mobile terminal is particularly important, userequestAnimationFrameand reducing DOM operations are effective ways to improve rolling performance. In addition, in mobile devices, excessive animation and scrolling event processing can also cause page stuttering, so special attention should be paid to the user experience.

6. Summary

Page scrolling events are an indispensable tool in web development. Through it, developers can realize rich user interaction functions, such as back to the top button, infinite scrolling loading, scrolling animations, etc. However, frequent triggering of rolling events may bring performance problems, so in actual development, it is crucial to reasonably optimize rolling event handling. Through the introduction of this article, I hope you can better master the skills of using page scrolling events and provide your project with a smoother user experience.

This is the end of this article about JavaScript page scrolling events. For more related contents of JS page scrolling events, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!