HTML5 Guidelines for Web Developers

(coco) #1
4.7 Video and Scripting—A Simple Video Player 95

4.7.8 Other Attributes and Methods of the “HTMLMediaElement”


Interface


All media elements (including not only video, but also audio) have five attributes
in common, which are shown in the HTMLMediaElement interface. Apart from src
as source of the media stream, there are the boolean attributes autoplay, loop,
and controls, plus preload with its three values none, metadata, and auto. The
code for dynamically creating a video could then look like this:


var video = document.createElement("VIDEO");
video.src = 'videos/bbb_240p_stereo.ogv';
video.autoplay = false;
video.loop = true;
video.controls = true;
video.preload = 'metadata';


But this video is not loaded yet. The loading process only starts with the next
method of the HTMLMediaElement interface, video.load(). To be able to see the
video in the browser, we need to append it to the DOM tree. So we add two lines
to our listing:


video.load();
document.documentElement.appendChild(video);


The dynamic counterpart of the oncanplay attribute of our video player’s video
element is an event listener with event type, callback function, and a flag that
determines if the event should become active in the capture phase or not. Con-
fused? Just use false for the third argument, which activates the event listener
in the bubbling phase instead. If you want to know the details of how the event
order works, look online at http://www.quirksmode.org/js/events_order.html.
Our event listener listens for the event canplay and then immediately starts play-
ing the film:


video.addEventListener("canplay", function() {
video.play();
}, false);


The HTML version of our brief code example can of course be found online at
http://html5.komplett.cc/code/chap_video/js_dynamicVideo_en.html.

NOTE
Free download pdf