-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.scroll.ts
108 lines (88 loc) · 2.6 KB
/
plugin.scroll.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { BaseOptions } from '../types'
import { PluginBuilder } from '../core'
import { BindResult } from '../../types'
/**
* Internal scroll plugin to add scroll functionality to the core, functionalities include:
* - Capture the exact percentage of the page scrolled.
* - Capture the x and y scroll depth.
* - Capture the scroll direction (up, down).
* - Capture the scroll speed.
* - Capture the scroll position.
* - Capture the scroll height.
* @extends PluginBuilder
*/
class ScrollPlugin extends PluginBuilder {
override key: string = 'scroll'
lastScrollTop: number = 0
override bind(_: BaseOptions): BindResult[] {
return [
{
name: 'scroll',
target: document,
event: 'scroll',
callback: () => {
return this.captureEvent()
},
options: false
}
]
}
/**
* A function to capture the scroll events on your site.
*/
private captureEvent(): Record<string, any> {
// getting the scroll direction
const direction = this.getScrollDirection()
// getting the scroll depth
const scrollDepth = {
x: window.scrollX,
y: window.scrollY
}
// getting the scroll percentage
const scrollPercentage = window.scrollY / (document.body.scrollHeight - window.innerHeight) * 100
// getting the scroll position
const scrollPosition = {
x: window.scrollX / (document.body.scrollWidth - window.innerWidth),
y: window.scrollY / (document.body.scrollHeight - window.innerHeight)
}
// getting the scroll speed
const scrollSpeed = {
x: window.scrollX - window.scrollX,
y: window.scrollY - window.scrollY
}
// getting the scroll size
const scrollSize = {
x: document.body.scrollWidth - window.innerWidth,
y: document.body.scrollHeight - window.innerHeight
}
// getting the scroll viewport
const scrollViewport = {
x: window.innerWidth,
y: window.innerHeight
}
// setting the scroll data
const payload = {
direction,
depth: scrollDepth,
percentage: scrollPercentage,
position: scrollPosition,
speed: scrollSpeed,
size: scrollSize,
viewport: scrollViewport
}
return payload
}
/**
* A function to get the scroll direction.
*/
private getScrollDirection = (): string => {
const st = window.pageYOffset || document.documentElement.scrollTop
if (st > this.lastScrollTop) {
this.lastScrollTop = st
return 'down'
}
this.lastScrollTop = st <= 0 ? 0 : st // For Mobile or negative scrolling
return 'up'
}
}
export default ScrollPlugin