scroll

The scroll event is fired when the document view or an element has been scrolled.

General info

Specification
DOM L3, CSSOM View
Interface
UIEvent
Bubbles
Not on elements, but bubbles to the default view when fired on the document
Cancelable
No
Target
defaultView, Document, Element
Default Action
None

Properties

Property Type Description
target Read only EventTarget The event target (the topmost target in the DOM tree).
type Read only DOMString The type of event.
bubbles Read only boolean Does the event normally bubble?
cancelable Read only boolean Is it possible to cancel the event?
view Read only WindowProxy document.defaultView (window of the document)
detail Read only long (float) 0.

Example

Since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame, setTimeout or customEvent, as follows:

requestAnimationFrame + customEvent

;(function() {
    var throttle = function(type, name, obj) {
        var obj = obj || window;
        var running = false;
        var func = function() {
            if (running) { return; }
            running = true;
            requestAnimationFrame(function() {
                obj.dispatchEvent(new CustomEvent(name));
                running = false;
            });
        };
        obj.addEventListener(type, func);
    };

    /* init - you can init any event */
    throttle ("scroll", "optimizedScroll");
})();

// handle event
window.addEventListener("optimizedScroll", function() {
    console.log("Resource conscious scroll callback!");
});

More similar examples on resize event.

Browser compatibility

iOS UIWebView

In iOS UIWebViews, scroll events are not fired while scrolling is taking place; they are only fired after the scrolling has completed. See Bootstrap issue #16202. Safari and WKWebViews are not affected by this bug.

Document Tags and Contributors

Contributors to this page: cvrebert, pantherCZ, teoli, Sheppy, ethertank, louisremi
Last updated by: cvrebert,