1
+ const doc = document
2
+ const win = window
3
+ const body = doc . body
4
+ const html = doc . documentElement
5
+ const ZERO = 0
6
+
7
+ /**
8
+ * Simple function convert in boolean any value and return true if its value was truthy
9
+ * @param {* } v - anything
10
+ * @returns { Boolean } true if truthy
11
+ */
12
+ const isTruthy = v => ! ! v
13
+
14
+ /**
15
+ * Get the max value from a list of arguments filtering the falsy values
16
+ * @param {...Number } args - list of numbers
17
+ * @returns { Number } the highest value
18
+ */
19
+ const max = ( ...args ) => Math . max ( ZERO , ...args . filter ( isTruthy ) , ZERO )
20
+
21
+ /**
22
+ * Return the size of the scrollbar that depends on the browser or device used on the client
23
+ * @returns { Number } - the browser scrollbar width
24
+ */
25
+ export function scrollbarWidth ( ) {
26
+ // Create the measurement node
27
+ const div = doc . createElement ( 'div' )
28
+ Object . assign ( div . style , {
29
+ width : '100px' ,
30
+ height : '100px' ,
31
+ overflow : 'scroll' ,
32
+ position : 'fixed' ,
33
+ opacity : '0'
34
+ } )
35
+
36
+ doc . body . appendChild ( div )
37
+ // Read values
38
+ const { offsetWidth, clientWidth } = div
39
+ // Delete helper element
40
+ doc . body . removeChild ( div )
41
+
42
+ return max ( offsetWidth - clientWidth )
43
+ }
44
+
45
+ /**
46
+ * Get the height of the whole page
47
+ * @returns { Number } height in px of the document
48
+ */
49
+ export function documentHeight ( ) {
50
+ return max (
51
+ body . scrollHeight ,
52
+ body . offsetHeight ,
53
+ html . clientHeight ,
54
+ html . scrollHeight ,
55
+ html . offsetHeight
56
+ )
57
+ }
58
+
59
+ /**
60
+ * Get the width of the whole page
61
+ * @returns { Number } width in px of the document
62
+ */
63
+ export function documentWidth ( ) {
64
+ return max (
65
+ body . scrollWidth ,
66
+ body . offsetWidth ,
67
+ html . clientWidth ,
68
+ html . scrollWidth ,
69
+ html . offsetWidth
70
+ )
71
+ }
72
+
73
+ /**
74
+ * Return amount of px scrolled from the top of the document
75
+ * @returns { Number } scroll top value in px
76
+ */
77
+ export function scrollTop ( ) {
78
+ return max (
79
+ win . scrollY ,
80
+ win . pageYOffset ,
81
+ doc . documentElement . scrollTop
82
+ )
83
+ }
84
+
85
+ /**
86
+ * Return amount of px scrolled from the top of the document
87
+ * @returns { Number } scroll top value in px
88
+ */
89
+ export function scrollLeft ( ) {
90
+ return max (
91
+ win . scrollX ,
92
+ win . pageXOffset ,
93
+ doc . documentElement . scrollLeft
94
+ )
95
+ }
96
+
97
+
98
+ /**
99
+ * Get the offset top of any DOM element
100
+ * @param { HTMLElement } el - the element we need to check
101
+ * @returns { Number } the element y position in px
102
+ */
103
+ export function elementOffsetTop ( el ) {
104
+ return max ( scrollTop ( ) + el . getBoundingClientRect ( ) . top )
105
+ }
0 commit comments