Video Duration and Current Play Time Programming Tutorial

Published :
Author :
Adam Khoury
In this 3rd part of customizing the HTML5 video controls we will demonstrate how you can show the current play time and the full video duration time the way youtube videos display video current time and duration. We can use the currentTime and duration properties of the video object and convert them to minutes and seconds for display purposes. <!DOCTYPE html> <html> <head> <style> div#video_player_box{ width:550px; background:#000; margin:0px auto;} div#video_controls_bar{ background: #333; padding:10px; color:#CCC;} </style> <script> var vid, playbtn, seekslider, curtimetext, durtimetext; function intializePlayer(){ // Set object references vid = document.getElementById("my_video"); playbtn = document.getElementById("playpausebtn"); seekslider = document.getElementById("seekslider"); curtimetext = document.getElementById("curtimetext"); durtimetext = document.getElementById("durtimetext"); // Add event listeners playbtn.addEventListener("click",playPause,false); seekslider.addEventListener("change",vidSeek,false); vid.addEventListener("timeupdate",seektimeupdate,false); } window.onload = intializePlayer; function playPause(){ if(vid.paused){ vid.play(); playbtn.innerHTML = "Pause"; } else { vid.pause(); playbtn.innerHTML = "Play"; } } function vidSeek(){ var seekto = vid.duration * (seekslider.value / 100); vid.currentTime = seekto; } function seektimeupdate(){ var nt = vid.currentTime * (100 / vid.duration); seekslider.value = nt; var curmins = Math.floor(vid.currentTime / 60); var cursecs = Math.floor(vid.currentTime - curmins * 60); var durmins = Math.floor(vid.duration / 60); var dursecs = Math.floor(vid.duration - durmins * 60); if(cursecs < 10){ cursecs = "0"+cursecs; } if(dursecs < 10){ dursecs = "0"+dursecs; } if(curmins < 10){ curmins = "0"+curmins; } if(durmins < 10){ durmins = "0"+durmins; } curtimetext.innerHTML = curmins+":"+cursecs; durtimetext.innerHTML = durmins+":"+dursecs; } </script> </head> <body> <div id="video_player_box"> <video id="my_video" width="550" height="310" autoplay> <source src="Tom_and_Jerry.mp4"> </video> <div id="video_controls_bar"> <button id="playpausebtn">Pause</button> <input id="seekslider" type="range" min="0" max="100" value="0" step="1"> <span id="curtimetext">00:00</span> / <span id="durtimetext">00:00</span> </div> </div> </body> </html>