Back to Posts

Media Elements

HTML 5 introduced support for audio and video natively in the browser (without plugins). This makes removes the need to use proprietary tools and formats (such as Flash, QuickTime, Windows Media, Real) in order to provide basic media capabilities.

Download this file to follow along in class


Video: Basic Tag Usage

<video width="720" height="480" src="video.mp4" controls />

Supporting Multiple Formats

<video width="720" height="480" controls>
	<source src="video.mp4" type="video/mp4">
	<source src="video.ogg" type="video/ogg">
	Your browser does not support the video tag.
</video>

Video Tag Attributes: autoplay, controls, height, width, loop, muted, poster, preload, src


Audio: Basic Tag Usage

<audio controls src="audio.mp3" />

Supporting Multiple Formats

<audio controls>
	<source src="audio.ogg" type="audio/ogg">
	<source src="audio.mp3" type="audio/mpeg">
	Your browser does not support the audio tag.
</audio>

Audio Tag Attributes: autoplay, controls, loop, preload, src


JavaScript with Video Functionality

Of course, there are a lot of features and functionality available via JavaScript.

w3schools.com - HTML Audio/Video DOM Reference

<html>
	<head>
		<meta charset="utf-8">
		<title>Video JavaScript</title>
	</head>
	<body>
		<!-- Add an “id” to the video tag 
		so that we can access it easily in JavaScript -->
		<video width="720" height="480" controls id="thevideo">
			<source src="video.mp4" type="video/webm">
		</video>
		
		<button id="btn">Do Something!</button>

		<!-- script tag at end of body so everything loads -->
		<script type="text/javascript">

			// get Access to the Video Object
			var theVideoObject = document.getElementById("thevideo");

			// alert, just to make sure it isn’t null
			alert(theVideoObject);

			<!-- When the button is clicked, 
			call the doSomething function -->
			document.getElementById("btn").addEventListener("mousedown", doSomething);

			// called by the Do Something button
			function doSomething() {
				// change the width
				theVideoObject.width = theVideoObject.width/2;

				if (theVideoObject.paused) {
					// if the video is paused, call play
	        			theVideoObject.play();
				} else {
	        			// otherwise, pause it
	        			theVideoObject.pause();
				}                
			}
		</script>
	</body>
</html>