-
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathscrollElementIntoView.ts
More file actions
38 lines (32 loc) · 1.3 KB
/
scrollElementIntoView.ts
File metadata and controls
38 lines (32 loc) · 1.3 KB
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
/**
* Scroll the element into the top of the viewport
*/
export default function scrollElementIntoView(element: HTMLElement, addressBarShadowPadding: number): number {
let currentPosition = 0
const htmlNode = document.documentElement
const bodyNode = document.body
// Apply new global style
const styleTag = document.createElement('style')
styleTag.innerHTML = '* { scroll-behavior: unset !important; }'
document.head.appendChild(styleTag)
// Determine the current scroll position
if (htmlNode.scrollTop > 0) {
currentPosition = htmlNode.scrollTop
} else if (bodyNode.scrollTop > 0) {
currentPosition = bodyNode.scrollTop
}
const { top } = element.getBoundingClientRect()
// BCR.top is viewport-relative, so the element's document position is
// currentPosition + top. Scroll there (minus padding) to place the
// element at the viewport top.
const yPosition = currentPosition + top - addressBarShadowPadding
// Scroll to the position
if (htmlNode.scrollHeight > htmlNode.clientHeight) {
htmlNode.scrollTop = yPosition
} else if (bodyNode.scrollHeight > bodyNode.clientHeight) {
bodyNode.scrollTop = yPosition
}
// Remove the injected style
document.head.removeChild(styleTag)
return currentPosition
}