-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrolllock-normal.js
71 lines (62 loc) · 1.88 KB
/
scrolllock-normal.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
69
70
71
(function() {
let observer;
let isConnected = false;
let originalBodyPosition;
function saveBodyPosition() {
originalBodyPosition = document.body.style.position;
}
function checkContentHeight() {
if (document.body.scrollHeight > window.innerHeight) {
unlockScroll();
} else {
lockScroll();
}
}
function lockScroll() {
saveBodyPosition();
document.body.style.overflow = 'hidden';
document.body.style.position = 'fixed';
document.body.style.width = '100%';
document.body.style.top = `-${window.scrollY}px`;
}
function unlockScroll() {
document.body.style.overflow = 'auto';
document.body.style.position = originalBodyPosition || 'static';
const scrollY = document.body.style.top;
document.body.style.top = '';
window.scrollTo(0, parseInt(scrollY || '0') * -1);
}
function connect() {
if (!isConnected) {
checkContentHeight();
window.addEventListener('resize', checkContentHeight);
observer = new MutationObserver(checkContentHeight);
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
isConnected = true;
}
}
function disconnect() {
if (isConnected) {
window.removeEventListener('resize', checkContentHeight);
observer.disconnect();
document.body.style.position = originalBodyPosition || 'static';
document.body.style.overflow = 'visible';
document.body.style.top = '';
window.scrollTo(0, 0);
isConnected = false;
}
}
document.addEventListener('DOMContentLoaded', connect);
window.scrollLock = {
checkContentHeight,
lockScroll,
unlockScroll,
disconnect,
connect
};
})();