aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/scroll.js
blob: f4ffc66e335a95ec0cd178c749790132a742f57f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * Provides means to hook into the scroll event. Registered callbacks are
 * called with the current scroll top and scroll left position so both
 * vertical and horizontal scroll events can be handled.
 *
 * Updates/calls to the callback are synchronized to screen refresh by using
 * the animation frame method (which will fallback to a timer based solution).
 */
const handlers = {};
let animId = false;

let lastTop = null;
let lastLeft = null;

function refresh() {
    const hasHandlers = Object.keys(handlers).length > 0;
    if (!hasHandlers && animId !== false) {
        window.cancelAnimationFrame(animId);
        animId = false;
    } else if (hasHandlers && animId === false) {
        animId = window.requestAnimationFrame(() => Scroll.executeHandlers());
    }
}

function engageScrollTrigger() {
    window.removeEventListener('scroll', refresh);
    window.addEventListener('scroll', refresh, {once: true});
}

const Scroll = {
    executeHandlers(only_these = []) {
        const scrollTop = document.scrollingElement.scrollTop;
        const scrollLeft = document.scrollingElement.scrollLeft;

        if (scrollTop !== lastTop || scrollLeft !== lastLeft) {
            for (const [index, handler] of Object.entries(handlers)) {
                if (only_these.length === 0 || only_these.includes(index)) {
                    handler(scrollTop, scrollLeft);
                }
            }

            lastTop  = scrollTop;
            lastLeft = scrollLeft;
        }

        animId = false;

        engageScrollTrigger();
    },
    addHandler(index, handler, immediate = false) {
        handlers[index] = handler;
        engageScrollTrigger();

        if (immediate) {
            Scroll.executeHandlers([index]);
        }
    },
    removeHandler(index) {
        delete handlers[index];
        engageScrollTrigger();
    }
};

export default Scroll;