forked from rage/java-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrackHeight.js
51 lines (45 loc) · 1.32 KB
/
trackHeight.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
// Used for animations
import { createGlobalStyle } from "styled-components"
createGlobalStyle`
.render-element-off-screen-for-measurement {
position: absolute !important;
top: -100000px !important;
height: auto !important;
}
`
const saveHeight = (element, height) => {
element.style.setProperty("--calculated-height", height)
}
const calculateElementHeightOffScreen = element => {
return new Promise(resolve => {
element.classList.add("render-element-off-screen-for-measurement")
setTimeout(() => {
const height = element.getBoundingClientRect().height
element.classList.remove("render-element-off-screen-for-measurement")
resolve(height)
}, 100)
})
}
const calculateElementHeight = async element => {
let { height } = element.getBoundingClientRect()
if (height === 0) {
height = await calculateElementHeightOffScreen(element)
}
saveHeight(element, height)
}
export const trackElementHeight = element => {
if (element === null) {
return
}
element.classList.add("track-element-height-changes-for-animations")
calculateElementHeight(element)
}
export default () => {
window.addEventListener("resize", () => {
document
.querySelectorAll(".track-element-height-changes-for-animations")
.forEach(e => {
calculateElementHeight(e)
})
})
}