-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrack-scroll-depth.ts
More file actions
38 lines (28 loc) · 1011 Bytes
/
track-scroll-depth.ts
File metadata and controls
38 lines (28 loc) · 1011 Bytes
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
import { Analytics } from './analytics';
const THRESHOLDS = [25, 50, 75, 100] as const;
export function trackScrollDepth(): () => void {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return () => {};
}
const tracked = new Set<number>();
const onScroll = () => {
const documentHeight = document.documentElement.scrollHeight;
const windowHeight = window.innerHeight;
const scrollTop = window.scrollY;
const maxScrollable = documentHeight - windowHeight;
if (maxScrollable <= 0) return;
const scrollPercent = Math.round((scrollTop / maxScrollable) * 100);
for (const threshold of THRESHOLDS) {
if (scrollPercent >= threshold && !tracked.has(threshold)) {
tracked.add(threshold);
Analytics.track('scroll_depth', {
percent: threshold,
});
}
}
};
window.addEventListener('scroll', onScroll, { passive: true });
return () => {
window.removeEventListener('scroll', onScroll);
};
}