-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
executable file
·68 lines (57 loc) · 2.51 KB
/
main.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
const rightCol = '.col-md-4';
const leftCol = '.col-md-8';
const navbar = '.navbar';
const target = '#the-target';
const accordion = '#accordion';
const targetMargin = 30;
function init() {
const getElementHeight = function (element) {
return document.querySelector(element).getBoundingClientRect().height
};
const getElementBottom = function (element) {
return document.querySelector(element).getBoundingClientRect().bottom
};
const getElementTop = function (element) {
return document.querySelector(element).getBoundingClientRect().top
};
const rightColSelector = document.querySelector(rightCol);
const mutationObserverConfig = {attributes: true, childList: true, subtree: true};
const navbarHeight = getElementHeight(navbar);
const sidebarHeight = getElementHeight(target);
const sidebarSelector = document.querySelector(target);
let stuckOffsetBottom = getElementBottom(leftCol) - targetMargin;
let sidebarOffsetTop = getElementBottom(accordion) + document.documentElement.scrollTop;
let leftColumnHeight = getElementHeight(leftCol);
let rightColumnHeight = getElementHeight(rightCol);
function fixBanner() {
if (leftColumnHeight > rightColumnHeight) {
if (document.documentElement.scrollTop + navbarHeight > sidebarOffsetTop) {
sidebarSelector.classList.add('fixed');
} else {
sidebarSelector.classList.remove('fixed');
}
if (sidebarHeight + navbarHeight >= stuckOffsetBottom) {
sidebarSelector.style.top = sidebarHeight - stuckOffsetBottom < 0 ? Math.abs(sidebarHeight - stuckOffsetBottom) + 'px' : '-' + (sidebarHeight - stuckOffsetBottom) + 'px';
} else {
sidebarSelector.style.top = navbarHeight + 'px';
}
}
}
function observerCallback() {
leftColumnHeight = getElementHeight(leftCol) + getElementTop(leftCol);
rightColumnHeight = getElementHeight(rightCol) + getElementTop(rightCol);
}
const columnObserver = new MutationObserver(observerCallback);
columnObserver.observe(rightColSelector, mutationObserverConfig);
fixBanner();
window.onscroll = function () {
stuckOffsetBottom = getElementBottom(leftCol) - targetMargin;
sidebarOffsetTop = getElementBottom(accordion) + document.documentElement.scrollTop;
fixBanner();
};
}
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
init();
}
};