Videos have finally become possible since the introduction of HTML5. It is VERY easy to work with videos as the good guys at W3C made a very simple API to use. Before you get started, please make sure to download the source code for this tutorial as it contains the video files for this tutorial.
<source src="media/vid.mp4" type="video/webm"></source>
<source src="media/vid.ogv" type="video/mp4"></source>
Your browser does not support HTML5 videos. Please upgrade your browser to enjoy our videos.
There are 2 ways to include a HTML5 video. You can use the src attribute for the video tag. However, this isn’t recommended as you can’t specify multiple sources if you have them. The sad part is that not all media types are supported in all browsers. The 2 formats you should always have is the WebM and MPEG-4 format.
To add a source, you use the <source> tag. You must specify 2 attributes. One is the source for the video and the other is the type. You can also add text in your <video> tags as it’ll display if the user’s browser doesn’t support HTML5 videos.
Let’s take it to the next step by adding some HTML attributes to our video tag. Update your video tag to this.
<video id="vid" autoplay controls loop>
Some of these are self-explanatory, but let’s learn what they do.
- autoplay – Once the video is finished downloading, then the video will autoplay.
- controls – This gives you controllers for the video such as play, pause, mute and full screen. These vary from browser to browser.
- loop – The video will play from the beginning once it’s finished playing.
Clear out your script and add this bit of code.
var vid = document.getElementById( 'vid' );
alert( "Autoplay? " + vid.autoplay +
" Controls? " + vid.controls +
" Source? " + vid.currentSrc +
" Duration? " + vid.duration +
" Muted? " + vid.muted);
First we must grab our video. After that, we can start to get all the properties from it. There are A LOT of properties to go over, but here are just some of them. You can set the autoplay, controls and muted attributes to true or false if you like. By default, they’re false. For a list of all properties, then go here.
In our next tutorial, we’ll take a look at some video events we can use to play our video and add custom controls. For more information on the video element, then go here.