Reputation: 49
I need to find the viewed time of an HTML video from when a user clicks "play", to when click "pause"; at the moment I have found only the currentTime with a code like this, but this is not what I need:
$("video").on('timeupdate', function(){
console.log(this.currentTime);
});
Upvotes: 2
Views: 574
Reputation: 206028
"play"
Store a Date.now()
ms value into the element data-start
attribute"pause"
calculate the difference from Date.now()
and data-start
data-viewtime
attribute for later reference and addition.const EL_video = document.querySelector("#vid");
EL_video.addEventListener("play", () => {
EL_video.dataset.start = Date.now();
});
EL_video.addEventListener("pause", () => {
const diff = Date.now() - EL_video.dataset.start;
EL_video.dataset.viewtime = (+EL_video.dataset.viewtime || 0) + diff;
console.log(`Total view time: ${EL_video.dataset.viewtime} ms`);
});
video {max-height: 150px;}
<video id="vid" src="https://raw.githubusercontent.com/Ahmetaksungur/aksvideoplayer/main/videos/video-360.mp4" controls></video>
Upvotes: 4