-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser-scroll.js
35 lines (27 loc) · 1.18 KB
/
browser-scroll.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
export function browserScroll(elementId, containerId = '') {
const elementNotFound = (id) => `Element with ID ${id} not found.`;
function getOffsetTop(element) {
let offset = 0;
while (element != null) {
offset += element.offsetTop;
element = element.offsetParent;
}
return offset;
}
const elementToBeShown = document.getElementById(elementId);
if (!elementToBeShown) return elementNotFound(elementId);
// If container is not passed, scroll with respect to window.
const offsetElem = getOffsetTop(elementToBeShown);
if (containerId === '') {
window.scrollTo && window.scrollTo({ top: offsetElem, behavior: 'smooth' });
return `Element with ID ${elementId} scrolled with respect to window.`;
}
const container = document.getElementById(containerId);
if (!container) return elementNotFound(containerId);
const offsetContainer = getOffsetTop(container);
container.scrollTo && container.scrollTo({
top: offsetElem - offsetContainer,
behavior: 'smooth'
});
return `Element with ID ${elementId} scrolled with respect to container with id ${containerId}.`;
}