HTML5 - A Complete Reference
HTML5 - A Complete Reference
HTML5
New Elements New Attributes Full CSS3 Support Video and Audio 2D/3D Graphics Local Storage Local SQL Database Web Applications
Example
<!DOCTYPE HTML> <html> <body> <video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> </body> </html>
Try it yourself Click on the "Try it yourself" button to see how it works
What is HTML5?
HTML5 will be the new standard for HTML. The previous version of HTML, HTML 4.01, came in 1999. The web has changed a lot since then. HTML5 is still a work in progress. However, the major browsers support many of the new HTML5 elements and APIs.
New features should be based on HTML, CSS, DOM, and JavaScript Reduce the need for external plugins (like Flash) Better error handling More markup to replace scripting HTML5 should be device independent
<!DOCTYPE html>
<!DOCTYPE html> <html> <head> <title>Title of the document</title> </head> <body> The content of the document...... </body> </html>
The <canvas> element for 2D drawing The <video> and <audio> elements for media playback Support for local storage New content-specific elements, like <article>, <footer>, <header>, <nav>, <section> New form controls, like calendar, date, time, email, url, search
HTML5 References
At W3Schools you will find complete references about tags, global attributes, standard events, and more. HTML5 Reference
Tag <canvas>
Description Used to draw graphics, on the fly, via scripting (usually JavaScript)
Defines what to show in browsers that do not support ruby annotations Defines a section in a document Defines a date/time Defines a possible line-break
Removed Elements
The following HTML 4.01 elements are removed from HTML5:
<acronym> <applet> <basefont> <big> <center> <dir> <font> <frame> <frameset> <noframes> <strike> <tt>
HTML5 Canvas
Previous Next Chapter
The <canvas> element is used to draw graphics, on the fly, on a web page. Draw a red rectangle, a gradient rectangle, a multicolor rectangle, and some multicolor text onto the canvas:
What is Canvas?
The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <canvas> element. Note: Internet Explorer 8 and earlier versions, do not support the <canvas> element.
Create a Canvas
A canvas is a rectangular area on an HTML page, and it is specified with the <canvas> element. Note: By default, the <canvas> element has no border and no content. The markup looks like this:
Example
Example
<script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="#FF0000"; ctx.fillRect(0,0,150,75); </script>
Try it yourself Example explained: First, find the <canvas> element:
var c=document.getElementById("myCanvas");
Then, call its getContext() method (you must pass the string "2d" to the getContext() method):
var ctx=c.getContext("2d");
The getContext("2d") object is a built-in HTML5 object, with many properties and methods for drawing paths, boxes, circles, text, images, and more. The next two lines draw a red rectangle:
ctx.fillStyle="#FF0000"; ctx.fillRect(0,0,150,75);
The fillStyle property can be a CSS color, a gradient, or a pattern. The default fillStyle is #000000 (black). The fillRect(x,y,width,height) method draws a rectangle filled with the current fill style.
Canvas Coordinates
The canvas is a two-dimensional grid. The upper-left corner of the canvas has coordinate (0,0) So, the fillRect() method above had the parameters (0,0,150,75). This means: Start at the upper-left corner (0,0) and draw a 150x75 pixels rectangle. Coordinates Example Mouse over the rectangle below to see its x and y coordinates: X
Canvas - Paths
To draw straight lines on a canvas, we will use the following two methods:
moveTo(x,y) defines the starting point of the line lineTo(x,y) defines the ending point of the line
To actually draw the line, we must use one of the "ink" methods, like stroke().
Example
Define a starting point in position (0,0), and an ending point in position (200,100). Then use the stroke() method to actually draw the line: JavaScript:
ctx.lineTo(200,100); ctx.stroke();
Try it yourself To draw a circle on a canvas, we will use the following method:
arc(x,y,r,start,stop)
To actually draw the circle, we must use one of the "ink" methods, like stroke() or fill().
Example
Create a circle with the arc() method: JavaScript:
Canvas - Text
To draw text on a canvas, the most important property and methods are:
font - defines the font properties for text fillText(text,x,y) - Draws "filled" text on the canvas strokeText(text,x,y) - Draws text on the canvas (no fill)
Using fillText():
Example
Write a 30px high filled text on the canvas, using the font "Arial": JavaScript:
Example
Write a 30px high text (no fill) on the canvas, using the font "Arial": JavaScript:
Canvas - Gradients
Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors. There are two different types of gradients:
Once we have a gradient object, we must add two or more color stops. The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1. To use the gradient, set the fillStyle or strokeStyle property to the gradient, and then draw the shape, like a rectangle, text, or a line. Using createLinearGradient():
Example
Create a linear gradient. Fill rectangle with the gradient: JavaScript:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); // Create gradient var grd=ctx.createLinearGradient(0,0,200,0); grd.addColorStop(0,"red"); grd.addColorStop(1,"white"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,80);
Try it yourself Using createRadialGradient():
Example
Create a radial/circular gradient. Fill rectangle with the gradient: JavaScript:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); // Create gradient var grd=ctx.createRadialGradient(75,50,5,90,60,100); grd.addColorStop(0,"red"); grd.addColorStop(1,"white"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,80);
Try it yourself
Canvas - Images
To draw an image on a canvas, we will use the following method:
drawImage(image,x,y)
Image to use:
Example
Draw the image onto the canvas: JavaScript:
Previous
Next Chapter
What is SVG?
SVG stands for Scalable Vector Graphics SVG is used to define vector-based graphics for the Web SVG defines the graphics in XML format SVG graphics do NOT lose any quality if they are zoomed or resized Every element and every attribute in SVG files can be animated SVG is a W3C recommendation
SVG Advantages
Advantages of using SVG over other image formats (like JPEG and GIF) are:
can be created and edited with any text editor can be searched, indexed, scripted, and compressed are scalable can be printed with high quality at any resolution are zoomable (and the image can be zoomed without degradation)
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support inline SVG.
Example
<!DOCTYPE html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190"> <polygon points="100,10 40,180 190,60 10,60 160,180" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"> </svg> </body> </html>
Try it yourself Result: To learn more about SVG, please read our SVG Tutorial.
Resolution independent Support for event handlers Best suited for applications with large rendering areas (Google Maps) Slow rendering if complex (anything that uses the DOM a lot will be slow) Not suited for game applications
Previous
Next Chapter
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support drag and drop. Note: Drag and drop does not work in Safari 5.1.2.
Example
<!DOCTYPE HTML> <html> <head> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69"> </body> </html>
Try it yourself It might seem complicated, but lets go through all the different parts of a drag and drop event.
<img draggable="true">
event.preventDefault()
function drop(ev) {
Call preventDefault() to prevent the browser default handling of the data (default is open as link on drop) Get the dragged data with the dataTransfer.getData("Text") method. This method will return any data that was set to the same type in the setData() method The dragged data is the id of the dragged element ("drag1") Append the dragged element into the drop element
More Examples
Drag image back and forth How to drag (and drop) an image back and forth between two <div> elements.
Previous
Next Chapter
HTML5 Geolocation
Previous Next Chapter
HTML5 Geolocation is used to locate a user's position Try It
Browser Support
Internet Explorer 9+, Firefox, Chrome, Safari and Opera support Geolocation. Note: Geolocation is much more accurate for devices with GPS, like iPhone.
Example
<script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
} </script>
Try it yourself Example explained:
Check if Geolocation is supported If supported, run the getCurrentPosition() method. If not, display a message to the user If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter ( showPosition ) The showPosition() function gets the displays the Latitude and Longitude
The example above is a very basic Geolocation script, with no error handling.
Example
function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML="User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML="Location information is unavailable." break; case error.TIMEOUT: x.innerHTML="The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML="An unknown error occurred." break; } }
Try it yourself Error Codes:
Permission denied - The user did not allow Geolocation Position unavailable - It is not possible to get the current location Timeout - The operation timed out
Example
function showPosition(position) { var latlon=position.coords.latitude+","+position.coords.longitude; var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" +latlon+"&zoom=14&size=400x300&sensor=false"; document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>"; }
Try it yourself In the example above we use the returned latitude and longitude data to show the location in a Google map (using a static image). Google Map Script How to use a script to show an interactive map with a marker, zoom and drag options.
Location-specific Information
This page demonstrated how to show a user's position on a map. However, Geolocation is also very useful for location-specific information. Examples:
Up-to-date local information Showing Points-of-interest near the user Turn-by-turn navigation (GPS)
coords.altitudeAccuracy The altitude accuracy of position coords.heading coords.speed timestamp The heading as degrees clockwise from North The speed in meters per second The date/time of the response
Example
<script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script>
Try it yourself
HTML5 Video
Previous Next Chapter
Many modern websites show videos. HTML5 provides a standard for showing them. Check if your browser supports HTML5 video
Check
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <video> element. Note: Internet Explorer 8 and earlier versions, do not support the <video> element.
Example
<video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video>
Try it yourself The control attribute adds video controls, like play, pause, and volume. It is also a good idea to always include width and height attributes. If height and width are set, the space required for the video is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the video, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the video loads). You should also insert text content between the <video> and </video> tags for browsers that do not support the <video> element. The <video> element allows multiple <source> elements. <source> elements can link to different video files. The browser will use the first recognized format.
MP4 = MPEG 4 files with H264 video codec and AAC audio codec WebM = WebM files with VP8 video codec and Vorbis audio codec Ogg = Ogg files with Theora video codec and Vorbis audio codec
Example 1
Create simple play/pause + resize controls for a video:
HTML5 Audio
Previous Next Chapter
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <audio> element. Note: Internet Explorer 8 and earlier versions, do not support the <audio> element.
Example
<audio controls> <source src="horse.ogg" type="audio/ogg"> <source src="horse.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio>
Try it yourself
The control attribute adds audio controls, like play, pause, and volume. You should also insert text content between the <audio> and </audio> tags for browsers that do not support the <audio> element. The <audio> element allows multiple <source> elements. <source> elements can link to different audio files. The browser will use the first recognized format.
color date datetime datetime-local email month number range search tel time url
week
Note: Not all major browsers support all the new input types. However, you can already start using them; If they are not supported, they will behave as regular text fields.
Example
Select a color from a color picker:
Example
Define a date control:
Example
Define a date and time control (with time zone):
Example
Define a date and time control (no time zone):
Example
Define a field for an e-mail address (will be automatically validated when submitted):
Tip: Safari on iPhone recognizes the email type, and changes the on-screen keyboard to match it (adds @ and .com options).
Example
Define a month and year control (no time zone):
Example
Define a numeric field (with restrictions):
max - specifies the maximum value allowed min - specifies the minimum value allowed step - specifies the legal number intervals value - Specifies the default value
Example
Define a control for entering a number whose exact value is not important (like a slider control):
max - specifies the maximum value allowed min - specifies the minimum value allowed step - specifies the legal number intervals value - Specifies the default value
Example
Define a search field (like a site search, or Google search):
Try it yourself
Example
Define a control for entering a time (no time zone):
Example
Define a field for entering a URL:
Example
Define a week and year control (no time zone):
Note: Not all major browsers support all the new form elements. However, you can already start using them; If they are not supported, they will behave as regular text fields.
Example
An <input> element with pre-defined values in a <datalist>:
<input list="browsers"> <datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <option value="Chrome"> <option value="Opera"> <option value="Safari"> </datalist>
Try it yourself
Example
A form with a keygen field:
<form action="demo_keygen.asp" method="get"> Username: <input type="text" name="usr_name"> Encryption: <keygen name="security"> <input type="submit"> </form>
Try it yourself
Example
Perform a calculation and show the result in an <output> element:
<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0 <input type="range" id="a" value="50">100 + <input type="number" id="b" value="50">= <output name="x" for="a b"></output> </form>
Try it yourself
autocomplete novalidate
autocomplete autofocus form formaction formenctype formmethod formnovalidate formtarget height and width list min and max multiple pattern (regexp) placeholder required step
Example
An HTML form with autocomplete on (and off for one input field):
<form action="demo_form.asp" autocomplete="on"> First name:<input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> E-mail: <input type="email" name="email" autocomplete="off"><br>
Example
Indicates that the form is not to be validated on submit:
<form action="demo_form.asp" novalidate> E-mail: <input type="email" name="user_email"> <input type="submit"> </form>
Try it yourself
Example
Let the "First name" input field automatically get focus when the page loads:
Example
An input field located outside the HTML form (but still a part of the form):
<form action="demo_form.asp" id="form1"> First name: <input type="text" name="fname"><br> <input type="submit" value="Submit"> </form> Last name: <input type="text" name="lname" form="form1">
Try it yourself
Example
An HTML form with two submit buttons, with different actions:
<form action="demo_form.asp"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <input type="submit" value="Submit"><br> <input type="submit" formaction="demo_admin.asp" value="Submit as admin"> </form>
Try it yourself
Example
Send form-data that is default encoded (the first submit button), and encoded as "multipart/form-data" (the second submit button):
<form action="demo_post_enctype.asp" method="post"> First name: <input type="text" name="fname"><br> <input type="submit" value="Submit"> <input type="submit" formenctype="multipart/form-data" value="Submit as Multipart/form-data"> </form>
Try it yourself
Example
The second submit button overrides the HTTP method of the form:
<form action="demo_form.asp" method="get"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <input type="submit" value="Submit"> <input type="submit" formmethod="post" formaction="demo_post.asp" value="Submit using POST"> </form>
Try it yourself
Example
A form with two submit buttons (with and without validation):
<form action="demo_form.asp"> E-mail: <input type="email" name="userid"><br> <input type="submit" value="Submit"><br> <input type="submit" formnovalidate value="Submit without validation"> </form>
Try it yourself
Example
A form with two submit buttons, with different target windows:
<form action="demo_form.asp"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <input type="submit" value="Submit as normal"> <input type="submit" formtarget="_blank" value="Submit to a new window"> </form>
Try it yourself
Example
Define an image as the submit button, with height and width attributes:
Example
An <input> element with pre-defined values in a <datalist>:
<input list="browsers"> <datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <option value="Chrome"> <option value="Opera"> <option value="Safari"> </datalist>
Try it yourself
Example
Enter a date before 1980-01-01: <input type="date" name="bday" max="1979-12-31"> Enter a date after 2000-01-01: <input type="date" name="bday" min="2000-01-02"> Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
Try it yourself
Example
A file upload field that accepts multiple values:
Example
An input field that can contain only three letters (no numbers or special characters):
Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
Try it yourself
Example
An input field with a placeholder text:
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
Example
A required input field:
Example
An input field with a specified legal number intervals:
Previous
Next Chapter
Browser Support
Internet Explorer 9+, Firefox, Chrome, Safari and Opera supports the semantic elements described in this chapter. Note: Internet Explorer 8 and earlier does not support these elements. However, there is a solution. Look at the end of this chapter.
Example
<section> <h1>WWF</h1> <p>The World Wide Fund for Nature (WWF) is....</p> </section>
Try it yourself
Example
<article> <h1>Internet Explorer 9</h1> <p>Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14, 2011 at 21:00 PDT.....</p> </article>
Try it yourself
Example
<nav> <a href="/html/">HTML</a> | <a href="/css/">CSS</a> | <a href="/js/">JavaScript</a> | <a href="/jquery/">jQuery</a> </nav>
Try it yourself
Example
<p>My family and I visited The Epcot center this summer.</p> <aside> <h4>Epcot Center</h4> <p>The Epcot Center is a theme park in Disney World, Florida.</p> </aside>
Try it yourself
Example
<article> <header> <h1>Internet Explorer 9</h1> <p><time pubdate datetime="2011-03-15"></time></p> </header> <p>Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14, 2011 at 21:00 PDT.....</p> </article>
Try it yourself
Example
<footer> <p>Posted by: Hege Refsnes</p> <p><time pubdate datetime="2012-03-01"></time></p> </footer>
Try it yourself
The <figcaption> tag defines a caption for a <figure> element. The <figcaption> element can be placed as the first or last child of the <figure> element.
Example
<figure> <img src="img_pulpit.jpg" alt="The Pulpit Rock" width="304" height="228"> <figcaption>Fig1. - The Pulpit Pock, Norway.</figcaption> </figure>
Try it yourself
Browser Support
Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari. Note: Internet Explorer 7 and earlier versions, do not support web storage.
localStorage - stores data with no expiration date sessionStorage - stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage)!=="undefined") { // Yes! localStorage and sessionStorage support! // Some code..... } else { // Sorry! No web storage support.. }
Example
localStorage.lastname="Smith"; document.getElementById("result").innerHTML="Last name: " + localStorage.lastname;
Try it yourself Example explained:
Create a localStorage key/value pair with key="lastname" and value="Smith" Retrieve the value of the "lastname" key and insert it into the element with id="result"
Tip: Key/value pairs are always stored as strings. Remember to convert them to another format when needed. The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:
Example
if (localStorage.clickcount) { localStorage.clickcount=Number(localStorage.clickcount)+1; } else { localStorage.clickcount=1; } document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
Try it yourself
Example
if (sessionStorage.clickcount) { sessionStorage.clickcount=Number(sessionStorage.clickcount)+1; } else { sessionStorage.clickcount=1; } document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
Try it yourself
Previous
Next Chapter
With HTML5 it is easy to make an offline version of a web application, by creating a cache manifest file.
Browser Support
Internet Explorer 10, Firefox, Chrome, Safari and Opera support Application cache.
Example
<!DOCTYPE HTML> <html manifest="demo.appcache"> <body> The content of the document...... </body>
</html>
Try it yourself
CACHE MANIFEST - Files listed under this header will be cached after they are downloaded for the first time NETWORK - Files listed under this header require a connection to the server, and will never be cached FALLBACK - Files listed under this header specifies fallback pages if a page is inaccessible
CACHE MANIFEST
The first line, CACHE MANIFEST, is required:
NETWORK
The NETWORK section below specifies that the file "login.asp" should never be cached, and will not be available offline:
NETWORK: login.asp
An asterisk can be used to indicate that all other resources/files require an internet connection:
NETWORK: *
FALLBACK
The FALLBACK section below specifies that "offline.html" will be served in place of all files in the /html/ catalog, in case an internet connection cannot be established:
The user clears the browser's cache The manifest file is modified (see tip below) The application cache is programmatically updated
Browser Support
Internet Explorer 10, Firefox, Chrome, Safari and Opera support Web workers.
Example
Count numbers: Start Worker Stop Worker
Try it yourself
if(typeof(Worker)!=="undefined") { // Yes! Web worker support! // Some code..... } else { // Sorry! No Web Worker support.. }
w.onmessage=function(event){ document.getElementById("result").innerHTML=event.data; };
When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.
w.terminate();
Example
<!DOCTYPE html> <html> <body> <p>Count numbers: <output id="result"></output></p> <button onclick="startWorker()">Start Worker</button> <button onclick="stopWorker()">Stop Worker</button> <br><br> <script> var w; function startWorker() { if(typeof(Worker)!=="undefined") { if(typeof(w)=="undefined") { w=new Worker("demo_workers.js"); } w.onmessage = function (event) { document.getElementById("result").innerHTML=event.data; }; } else { document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers..."; } } function stopWorker() { w.terminate(); } </script> </body> </html>
Try it yourself
Browser Support
Server-Sent Events are supported in all major browsers, except Internet Explorer.
Example
var source=new EventSource("demo_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br>"; };
Try it yourself Example explained:
Create a new EventSource object, and specify the URL of the page sending the updates (in this example "demo_sse.php") Each time an update is received, the onmessage event occurs When an onmessage event occurs, put the received data into the element with id="result"
if(typeof(EventSource)!=="undefined") { // Yes! Server-sent events support! // Some code..... } else { // Sorry! No server-sent events support.. }
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}\n\n"; flush(); ?>
Code in ASP (VB) (demo_sse.asp):
Set the "Content-Type" header to "text/event-stream" Specify that the page should not cache Output the data to send (Always start with "data: ") Flush the output data back to the web page
HTML Multimedia
Previous Next Chapter
Multimedia on the web is sound, music, videos, and animations. Modern web browsers have support for many multimedia formats.
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see. Examples: Pictures, music, sound, videos, records, films, animations, and more. Modern Web pages have often embedded multimedia elements, and modern browsers have support for various multimedia formats. In this tutorial you will learn about different multimedia formats.
Browser Support
The first Internet browsers had support for text only, and even the text support was limited to a single font in a single color. Then came browsers with support for colors, fonts and text styles, and support for pictures was added. The support for sounds, animations, and videos is handled in different ways by various browsers. Some multimedia elements is supported, and some requires an extra helper program (a plug-in). You will learn more about plug-ins in the next chapters.
Multimedia Formats
Multimedia elements (like sounds or videos) are stored in media files. The most common way to discover the type of a file, is to look at the file extension. When a browser sees the file extension .htm or .html, it will treat the file as an HTML file. The .xml extension indicates an XML file, and the .css extension indicates a style sheet file. Pictures are recognized by extensions like .gif, .png and .jpg. Multimedia files also have their own formats with different extensions like: .swf, .wav, .mp3, and .mp4.
Video Formats
MP4 is the new and upcoming format for internet video. It is supported by YouTube, Flash players and HTML5.
Format AVI
File .avi
Description AVI (Audio Video Interleave) was developed by Microsoft. AVI is supported by all computers running Windows, and by the most popular web browsers. It is a very common format on the Internet, but not always possible to play on non-Windows computers WMV (Windows Media Video) was developed by Microsoft. WMV is a common format on the Internet, but it cannot be played on non-Windows computer without an extra (free) component installed. Some later WMVs cannot play at all on non-Windows computers because no player is available
WMV
.wmv
MPEG
.mpg The MPEG (Moving Pictures Expert Group) format is the most popular format on the Internet. It .mpeg is cross-platform, and supported by all major browsers QuickTime was developed by Apple. QuickTime is a common format on the Internet, but QuickTime movies cannot be played on a Windows computer without an extra (free) component installed. RealVideo was developed by Real Media. RealVideo allows streaming of video (online video, Internet TV) with low bandwidths. Because of the low bandwidth priority, the quality is often
QuickTime .mov
RealVideo
.rm .ram
reduced Flash .swf .flv .mp4 Flash was developed by Macromedia. Flash requires an extra component to play. This component comes preinstalled with all major browsers Mpeg-4 (MP4) is the new format for the internet. YouTube recommends using MP4. YouTube accepts multiple formats, and then converts them all to .flv or .mp4 for distribution
MP4
Sound Formats
MP3 is the newest format for compressed recorded music. The term MP3 has become synonymous with digital music. If your website is about recorded music, the MP3 format is Format File Description the choice. MIDI .mid MIDI (Musical Instrument Digital Interface) is a format for electronic music devices like .midi synthesizers and PC sound cards. MIDI files do not contain sound, but digital musical instructions (notes) that can be played by electronics (like your PC's sound card).
Next
HTML
MP3
Click here to play The Beatles. Since MIDI files only contains instructions; they are extremely small. The example above is only 23K in size, but it plays for nearly 5 minutes. MIDI is supported by many software systems/platforms. MIDI is supported by all the most popular Internet browsers. .mp3 MP3 files are actually the sound part of MPEG files. MPEG was originally developed for video by the Moving Pictures Experts Group. MP3 is the most popular format for music. The encoding system combines good compression (small files) with high quality RealAudio was developed Real Media. It allows streaming of audio (online music, Internet radio) with low bandwidths. Because of the low bandwidth priority, the quality is often reduced WAVE (more known as WAV) was developed by IBM and Microsoft. WAVs are compatible with Windows, Macintosh, and Linux operating systems
Previous Chapter
- The
WMA
.wma WMA (Windows Media Audio), compares in quality to MP3, and is compatible with most players, except the iPod. WMA files can be delivered as a continuous flow of data, which makes it practical for use in Internet radio or on-line music.
<object> Element
Previous Next Chapter
The purpose of the <object> element is to support HTML helpers (plug-ins).
Example
<object width="100%" height="100%" type="video/x-ms-asf" url="3d.wmv" data="3d.wmv" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"> <param name="url" value="3d.wmv"> <param name="filename" value="3d.wmv"> <param name="autostart" value="1"> <param name="uiMode" value="full"> <param name="autosize" value="1"> <param name="playcount" value="1"> <embed type="application/x-mplayer2" src="3d.wmv" width="100%" height="100%" autostart="true" showcontrols="true" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"></embed> </object>
Try it yourself
Plug-ins
Plug-ins can be used for many purposes: to display maps, scan for viruses, verify your bank id, and much more. The restrictions are few.
HTML Audio
Previous Next Chapter
Using Plug-ins
A plug-in is a small computer program that extends the standard functionality of the browser. Plug-ins can be added to HTML pages using the <object> tag or the <embed> tag. These tags define containers for resources (normally non-HTML resources), which, depending on the type, will either be displayed by the browsers, or by an external plug-in.
Example
<embed height="50" width="100" src="horse.mp3">
Try it yourself
Problems:
Different browsers support different audio formats If a browser does not support the file format, the audio will not play without a plug-in If the plug-in is not installed on the users' computer, the audio will not play If you convert the file to another format, it will still not play in all browsers
Example
<object height="50" width="100" data="horse.mp3"></object>
Try it yourself
Problems:
Different browsers support different audio formats If a browser does not support the file format, the audio will not play without a plug-in If the plug-in is not installed on the users' computer, the audio will not play If you convert the file to another format, it will still not play in all browsers
Example
<audio controls> <source src="horse.mp3" type="audio/mpeg"> <source src="horse.ogg" type="audio/ogg"> Your browser does not support this audio format. </audio>
Try it yourself
Problems:
Example
<audio controls height="100" width="100"> <source src="horse.mp3" type="audio/mpeg"> <source src="horse.ogg" type="audio/ogg"> <embed height="50" width="100" src="horse.mp3"> </audio>
Try it yourself
Problems:
You must convert the audio files into different formats The <embed> element cannot "fall-back" to display an error message
Example
<a href="horse.mp3">Play Sound</a> <script src="http://mediaplayer.yahoo.com/js"></script>
Try it yourself To use it, insert the following JavaScript at the bottom of your web page:
<script src="http://mediaplayer.yahoo.com/js"></script>
Then, simply link to your audio files in your HTML, and the JavaScript code automatically creates a play button for each song: <a href="song1.mp3">Play Song 1</a> <a href="song2.wav">Play Song 2</a> ... ... The Yahoo Media Player presents your readers with a small play button instead of a full player. However, when you click the button, a full player pops up. Note that the player is always docked and ready at the bottom of the window. Just click on it to slide it out.
Using A Hyperlink
If a web page includes a hyperlink to a media file, most browsers will use a "helper application" to play the file. The following code fragment displays a link to an MP3 file. If a user clicks on the link, the browser will launch a helper application to play the file:
Example
<a href="horse.mp3">Play the sound</a>
Try it yourself
If you plan to use inline sounds, be aware that many people will find it annoying. Also note that some users might have turned off the inline sound option in their browser. Our best advice is to include inline sounds only in pages where the user expects to hear sounds. An example of this is a page which opens after the user has clicked on a link to hear a recording.
Defines multiple media resources for media elements (<video> and <audio>) Defines text tracks for media elements (<video> and <audio>)
HTML Videos
Previous Next Chapter
Videos can be played in HTML by many different methods.
The following HTML fragment displays a Flash video embedded in a web page:
Example
<embed src="intro.swf" height="200" width="200">
Try it yourself Problems
If the browser does not support Flash, the video will not play iPad and iPhone do not support Flash videos If you convert the video to another format, it will still not play in all browsers
Example
<object data="intro.swf" height="200" width="200"></object>
Try it yourself Problems:
If the browser does not support Flash, the video will not play iPad and iPhone do not support Flash videos If you convert the video to another format, it will still not play in all browsers
Example
<video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> <source src="movie.webm" type="video/webm"> Your browser does not support the video tag. </video>
Try it yourself Problems:
You must convert your videos to many different formats The <video> element does not work in older browsers
Using A Hyperlink
If a web page includes a hyperlink to a media file, most browsers will use a "helper application" to play the file. The following code fragment displays a link to a Flash video. If a user clicks on the link, the browser will launch a helper application to play the file:
Example
<a href="intro.swf">Play a video file</a>
Try it yourself
Previous
Next Chapter