I am trying to show the time on hover of seek bar of a html5 video. ( similar to how youtube does it). I have tried to use the timeupdate event on the video as below but looks like there is more to it.
<script>
function myFunction(event) {
// The currentTime property
document.getElementById("demo").innerHTML = event.currentTime;
var video = event;
video.addEventListener('progress', function() {
var bufferedEnd = video.buffered.end(video.buffered.length - 1);
var duration = video.duration.toFixed(1);
alert(duration);
if (duration > 0) {
document.getElementById('buffered-amount').style.width = ((bufferedEnd / duration)*100) + "%";
}
});
// display the current and remaining times
video.addEventListener("timeupdate", function () {
// Current time
var vTime = video.currentTime;
var vLength = video.duration.toFixed(1);
document.getElementById("curTime").textContent = vTime.toFixed(1);
document.getElementById("vRemaining").textContent = (vLength - vTime).toFixed(1);
}, false);
}
</script>
html:
<source src="mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<div class="buffered">
<span id="buffered-amount"></span>
</div>
<div class="progress">
<span id="progress-amount"></span>
</div>
<p>Playback position: <span id="demo"></span></p>
<p>Current Time: <span id="curTime"></span></p>
<p>Remaining Time: <span id="vRemaining"></span></p>
I did try to understand multiple posts but did not find a solution. Do I need to use onmouseover event instead? How do I calculate the time of the video frame when the user positions the mouse on the slider?
Try using
controls
attribute. You will get similar control bar that is present on YouTube videos.Example in code.pen:(wait for video to load) http://codepen.io/mikemoney/pen/QdQvXY
Example on SO: (wait for video to load)
I would make a custom controls something like this: Using the width of the controls div and
video.duration
to calculate the new time.Hope this helps!
edit: to clarify my answer
If you look at the code:
e.clientX / controls.clientWidth * video.duration
you will see thate.clientX
is the current x position of your mouse on the controls rectangle.controls.clientWidth
is the total width of the controls rectangle.video.duration
is the total time of the video.so if I would put my mouse on the end of the of the rectanlge. I would get 100% of the video duration. and in the beginning I would get 0%. if I would put my mouse at exactly in the middle I would get exactly the time of the middle of the video.
with
video.currentTime
I can change the current time of the video so that the frame is exactly the right frame of the time.