HTML5 Guidelines for Web Developers

(coco) #1

90 Chapter 4—Video and Audio


curPos = document.getElementById("currentPosition");
curPos.max = video.duration;

This now gives max the value 596.468017578125, which means the video is about
ten-minutes long. Setting the playback position directly is done in the onchange
event handler callback updateProgress()when the slider is dragged or clicked:

var updateProgress = function(ctrl) {
video.currentTime = ctrl.value;
};

A single instruction is sufficient here; the attribute video.currentTime not only
reflects the current playback position, but can also be set directly. We get the
suitable value from the slider’s value attribute. To implement the display of the
current playback position in the format MM:SS, we still need the following steps:


  1. Add a span element in connection with the slider:

  2. Save a reference to the span in the initControls() function and initialize
    this variable curTime with the value 0:00:
    curTime = document.getElementById("timePlayed");
    curTime.innerHTML = '0:00';

  3. Update the timestamp curTime at each call of updateProgress():
    mm = Math.floor(video.currentTime / 60.0);
    ss = parseInt(video.currentTime) % 60;
    ss = (ss < 10)? '0'+ss : ss;
    curTime.innerHTML = mm+':'+ss;


We are nearly finished. Only one essential slider feature is still missing: While the
video is playing, it has to stay synchronized with the running time. The solution
lies in the HTML code for integrating the video: ontimeupdate. The specification
states that a timeupdate event should be triggered at intervals of at least 15 and
up to 250 milliseconds during media stream playback. The event handler attri-
bute ontimeupdate determines which callback function is called. If we set it to
updateProgress(), we have found the perfect timer for synchronizing our slider.
Compared to setting the position manually by clicking or dragging the slider, we
now must not change the playback position but instead set the slider and the
time display to the value of video.currentTime. The slightly adapted and thus
final version of our updateProgress() function is shown in Listing 4.1:
Free download pdf