runnerDev
runnerDev

Reputation: 49

HTML5 video: need to find viewed time from "play" to "pause" with javascript

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

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

  • On video "play" Store a Date.now() ms value into the element data-start attribute
  • On video "pause" calculate the difference from Date.now() and data-start
  • Store the cumulative ms result into 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

Related Questions