-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuser-behavior-analytics.js
More file actions
35 lines (32 loc) · 1.23 KB
/
user-behavior-analytics.js
File metadata and controls
35 lines (32 loc) · 1.23 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
document.addEventListener('DOMContentLoaded', () => {
const sections = document.querySelectorAll('.content-section');
const sectionVisibilityStartTimes = {};
const observedSections = new Set();
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const id = entry.target.id;
if (entry.isIntersecting) {
// Mark the start time if not already marked
if (!sectionVisibilityStartTimes[id]) {
sectionVisibilityStartTimes[id] = Date.now();
observedSections.add(id);
}
} else {
// Calculate duration and log it if the section was previously observed
if (observedSections.has(id)) {
const duration = Date.now() - sectionVisibilityStartTimes[id];
console.log(`${id} was visible for ${duration} milliseconds`);
// Reset or remove from observed to prevent duplicate logs
delete sectionVisibilityStartTimes[id];
observedSections.delete(id);
// Here, you might send this data to your analytics backend
}
}
});
}, {
threshold: 0.5 // Consider a section 'viewed' when 50% is visible
});
sections.forEach(section => {
observer.observe(section);
});
});