I am looking for to calculate how much time a visitor read my post using JavaScript. Like I have
3 div. each div contains information when visitor read any div I will calculate the time. it will not work when somebody scroll down not staying on the div. User must stay on the div. Each particular div will generate its own reading time. Actually I did not implement any code. Looking for a better solution. Thank you
You can use some web analytics services like google analytics
or hotjar
that provide a good services.
If you want to do something custom that match exactly you use case
I'd suggest using IntersectionObserver
API
const onIntersection = (entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
console.log(entry);
}
}
};
const observer = new IntersectionObserver(onIntersection);
observer.observe(document.querySelector('#div1'));
This will tell you when the viewport is on the selected element #div1
in this case (When the user is seeing the div). So you can run a timer and check how long the user has been viewing the element.
Useful links: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.