2 min read

Mastering Scroll Events: An Introduction to scrollend in JavaScript

Table of Contents

I’ve been waiting for this feature for ages!

In the past, when handling scroll behavior, the scroll event triggered too frequently, so we would always use setTimeout to optimize it.

Now that browsers support the scrollend event, it’s no longer necessary to go through such trouble.

Currently, Firefox and Chrome support this feature natively, but for Safari, a polyfill is still required (which will be demonstrated later in this article).

caniuse


Effect Demonstration

As long as you’re using a non-Safari browser (or a non-iPhone device), you can scroll inside the embedded container below to experience the scrollend effect.

If you touch without scrolling, the scrollend event will not be triggered.


How to Use and Browser Compatibility

It works the same way as the scroll event and can be applied to standard DOM elements as well as the global window object.

e.g.

window.addEventListener("scrollend", (event) => {
  // start scorll
});

element.addEventListener("scrollend", (event) => {
  // start scroll
});

Polyfill and Progressive Enhancement

Safari still doesn’t support this feature, so the production environment still needs some extra code for compatibility. Here’s a simple way to implement it:

if ('onscrollend' in window) {
  document.onscrollend = callback
} else {
  document.onscroll = event => {
    clearTimeout(window.scrollEndTimer)
    window.scrollEndTimer = setTimeout(callback, 100)
  }
}