-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrollHelper.js
68 lines (59 loc) · 1.94 KB
/
scrollHelper.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = { 37: 1, 38: 1, 39: 1, 40: 1 };
function preventDefault(e) {
e.preventDefault();
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
// modern Chrome requires { passive: false } when adding event
var supportsPassive = false;
try {
window.addEventListener(
"test",
null,
Object.defineProperty({}, "passive", {
get: function () {
supportsPassive = true;
},
})
);
} catch (e) {}
var wheelOpt = supportsPassive ? { passive: false } : false;
var wheelEvent =
"onwheel" in document.createElement("div") ? "wheel" : "mousewheel";
// call this to Disable
export function disableScroll() {
window.addEventListener("DOMMouseScroll", preventDefault, false); // older FF
window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
window.addEventListener("touchmove", preventDefault, wheelOpt); // mobile
window.addEventListener("keydown", preventDefaultForScrollKeys, false);
}
// call this to Enable
export function enableScroll() {
window.removeEventListener("DOMMouseScroll", preventDefault, false);
window.removeEventListener(wheelEvent, preventDefault, wheelOpt);
window.removeEventListener("touchmove", preventDefault, wheelOpt);
window.removeEventListener("keydown", preventDefaultForScrollKeys, false);
}
export function isElementInViewport(el) {
// Special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight ||
document.documentElement.clientHeight) /* or $(window).height() */ &&
rect.right <=
(window.innerWidth ||
document.documentElement.clientWidth) /* or $(window).width() */
);
}