T.XL T.XL - 13 days ago 7
Javascript Question

Javascript current time function to work

I am trying to get my custom video controls to show the current time of the video. However I can not get it to function. What am I missing in my code?

Javascript Code

var time = document.getElementById("current");

time.addEventListener("timeupdate", currentTime, true);

// Current time function

function currentTime() {

var currentMinutes = Math.floor(video.currentTime / 60);
var currentSeconds = Math.floor(video.currentTime - currentMinutes * 60);


time.innerHTML = currentMinutes + ":" + currentSeconds;

}


HTML5

<div id="time">
<span id="current">00:00</span>
<span id="duration">00:00</span>
</div>

Answer

You need to have an event trigger off the event. Since you're using a video, I would use the video ontimeupdate event.

There appears to be something wrong with the time displaying. But I got the video event stuff working here in this fiddle: https://jsfiddle.net/83peL34r/

Javascript:

var time = document.getElementById("current");
var video = document.getElementById("video");

time.addEventListener("timeupdate", currentTime, true);
video.ontimeupdate = function() {currentTime()};

// Current time function 

function currentTime() {

    var currentMinutes = Math.floor(video.currentTime / 60);
    var currentSeconds = Math.floor(video.currentTime - currentMinutes * 60);


  time.innerHTML = currentMinutes + ":" + currentSeconds;

}

HTML:

<video id="video" width="400" controls>
  <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
<div id="time">
  <span id="current">00:00</span> 
  <span id="duration">00:00</span>
</div>

Edit: I've made some changes to get you a little further. In this one, it grabs the duration and puts it in the duration section. And if the seconds is less than 10 it pads it with a 0 in front of it.

https://jsfiddle.net/83peL34r/1/