Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event after scrollling scrollbars or mousewheel with javascript

I would like to know if it is possible to fire an event after the scrolling of a page, when using the scrollbar or mouse-wheel (or with a swipe on a touch device).

Basically, I'd like to detect when the user has stopped scrolling so I can then AJAX-load, rather than loading while scrolling.

It seems that jQuery's .scroll() is firing every time a user scrolls, and it seems clunky to have an event fire all the time. Is there such thing as .onScrollAfter(), synonymous to the .onMouseUp()?

I'd like to know whether this is possible (or if a function already exists) without using a framework, though I would consider one; especially jQuery.

like image 299
Joseph Avatar asked Jan 19 '12 18:01

Joseph


People also ask

How do I use Onscroll event?

Definition and Usage. The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.

How often does scroll event fire?

Limit the minimum execution interval time of ONSCROLL event The onscroll event trigger interval time is around 10~20ms when we scrolling the mouse wheel.


1 Answers

This event does not exist. You can emulate it by using timeouts:

Example (concept code):

(function() {
    var timer;
    /* Basic "listener" */
    function scroll_finish(ev) {
        clearTimeout(timer);
        timer = setTimeout(scroll_finished, 200, ev);
        //200ms. Too small = triggered too fast. Too high = reliable, but slow
    }
    window.onscroll = scroll_finish; // Or addEventListener, it's just a demo

    // Fire "events"
    var thingey = [];
    function scroll_finished(ev) {
        // Function logic
        for (var i=0; i<thingey.length; i++) {
            thingey[i](ev);
        }
    }
    // Add listener
    window.addScrollListener = function(fn) {
        if (typeof fn  === 'function') {
            thingey.push(fn);
        } else {
           throw TypeError('addScrollListener: First argument must be a function.');
        }
    }
    window.removeScrollListener = function(fn) {
        var index = thingey.indexOf(fn);
        if (index !== -1) thingey.splice(index, 1);
    }
})();
like image 68
Rob W Avatar answered Oct 07 '22 18:10

Rob W