summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/eyeballs_off/utils/passive_event_listener.js
blob: 7b0285d4f865efb95492871be4c40b385cdb3c66 (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
/**
 * Tests for passive scroll support
 * Copied from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
 */
let supportsPassiveOption = false;
try {
  const opts = Object.defineProperty({}, 'passive', {
    get: () => {
      supportsPassiveOption = true;
    },
  });
  window.addEventListener('test', null, opts);
} catch (e) {
  /* */
}

/**
 * Attempts to add a passive scroll listener if possible,
 * otherwise adds a non-capture listeners
 */
export const addEventListener = (target, type, handler) => {
  let optionsOrCapture;

  if (supportsPassiveOption) {
    optionsOrCapture = { passive: true };
  } else {
    optionsOrCapture = false;
  }

  target.addEventListener(type, handler, optionsOrCapture);
};

export const removeEventListener = (target, type, handler) => {
  let optionsOrCapture;

  if (supportsPassiveOption) {
    optionsOrCapture = { passive: true };
  } else {
    optionsOrCapture = false;
  }

  target.removeEventListener(type, handler, optionsOrCapture);
};