HTML and CSS Reference
In-Depth Information
The code binds to the progress event, and when it fires, it gets
the percentage of video that can be played back compared to
the length of the video. Note the keyword
this
refers to the
video
element, as that's the context in which the
updateSeekable
function will be executed. The
duration
attribute is the length of
the media in seconds.
However, there's some issues with Firefox. In previous versions
the seekable length didn't match the actual duration, and in the
latest version (5.0.1) seekable seems to be missing altogether.
So to protect ourselves from the seekable time range going a
little awry, we can also listen for the progress event and default
to the duration of the video as backup:
video.addEventListener('durationchange', updateSeekable,
¬ false);
video.addEventListener('progress', updateSeekable, false);
function updateSeekable() {
buffer.style.width = (100 / (this.duration || 1) *
(this.seekable && this.seekable.length ? this.seekable.
¬ end() : this.duration)) + '%';
}
It's a bit rubbish that we can't reliably get the seekable range.
Alternatively we could look to the
video.buffered
property,
but sadly since we're only trying to solve a Firefox issue,
this value in Firefox (currently) doesn't return anything for the
video.buffered.end()
method—so it's not a suitable alternative.
When the media file is ready to play
When your browser first encounters the video (or audio) element
on a page, the media file isn't ready to be played just yet. The
browser needs to download and then decode the video (or audio)
so it can be played. Once that's complete, the media element will
fire the
canplay
event. Typically this is the time you would initialise
your controls and remove any “loading” indicator. So our code to
initialise the controls would typically look like this:
video.addEventListener('canplay', initialiseControls,
¬ false);
Nothing terribly exciting there. The control initialisation enables
the play/pause toggle button and resets the playhead in the
seek bar.