-
Notifications
You must be signed in to change notification settings - Fork 14
/
toggle-scrollbar.js
53 lines (46 loc) · 1.46 KB
/
toggle-scrollbar.js
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
// Key codes for navigation and control
const SCROLL_KEYS = {
'ArrowLeft': 1, 'ArrowUp': 1, 'ArrowRight': 1, 'ArrowDown': 1,
'PageUp': 1, 'PageDown': 1, 'End': 1, 'Home': 1, ' ': 1 // Spacebar
};
// Detect wheel event and passive support
const WHEEL_EVENT = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';
const WHEEL_OPT = (() => {
let supportsPassive = false;
try {
window.addEventListener("test", null, Object.defineProperty({}, 'passive', { get: () => supportsPassive = true }));
} catch (e) {}
return supportsPassive ? { passive: false } : false;
})();
// Prevent default behavior
function preventDefault(e) {
e.preventDefault();
}
// Prevent default behavior for scroll keys
function preventDefaultForScrollKeys(e) {
if (SCROLL_KEYS[e.key]) {
preventDefault(e);
return false;
}
}
// Register event listeners
function registerListeners(action) {
const method = action === 'add' ? 'addEventListener' : 'removeEventListener';
window[method]('DOMMouseScroll', preventDefault, false); // older FF
window[method](WHEEL_EVENT, preventDefault, WHEEL_OPT); // modern desktop
window[method]('touchmove', preventDefault, WHEEL_OPT); // mobile
window[method]('keydown', preventDefaultForScrollKeys, false);
}
// Disable scrolling
function disableScroll() {
registerListeners('add');
}
// Enable scrolling
function enableScroll() {
registerListeners('remove');
}
// Exports
module.exports = {
enableScroll,
disableScroll
};