Html5 Tutorial
Html5 Tutorial
Audience
This tutorial has been designed for beginners in HTML5 to make them understand the
basic-to-advanced concepts of the subject.
Prerequisites
Before starting this tutorial, you should have a basic understanding of HTML and its tags.
HTML5
<head>
<meta charset="utf-8">
<title>Tutorials Point</title>
</head>
<body>
<header role="banner">
<h1>HTML5 Document Structure Example</h1>
<p>This page should be tried in safari, chrome or Mozila.</p>
</header>
<footer>
<p>Created by <a href="http://tutorialspoint.com/">Tutorials
Point</a></p>
</footer>
</body>
</html>
HTML5
Table of Contents
About the Tutorial ................................................................................................................................... 1
Audience ................................................................................................................................................. 1
Prerequisites ........................................................................................................................................... 1
Execute HTML5 Online ............................................................................................................................ 2
Table of Contents .................................................................................................................................... 3
1.
HTML5 OVERVIEW............................................................................................................ 9
Browser Support ..................................................................................................................................... 9
New Features .......................................................................................................................................... 9
Backward Compatibility ........................................................................................................................ 10
2.
3.
4.
5.
HTML5
6.
HTML5 SVG..................................................................................................................... 35
Viewing SVG Files .................................................................................................................................. 35
Embedding SVG in HTML5 ..................................................................................................................... 35
HTML5 SVG Circle ............................................................................................................................... 36
HTML5 SVG Rectangle ........................................................................................................................ 36
HTML5 SVG Line ................................................................................................................................. 37
HTML5 SVG Ellipse .............................................................................................................................. 38
HTML5 SVG Polygon ........................................................................................................................... 39
HTML5 SVG Polyline ........................................................................................................................... 40
HTML5 SVG Gradients ........................................................................................................................ 40
HTML5 SVG Star ................................................................................................................................. 42
HTML5
7.
8.
9.
HTML5
HTML5
HTML5
1. HTML5 Overview
HTML5
HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML
1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the
World Wide Web.
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web
Hypertext Application Technology Working Group (WHATWG).
The new standard incorporates features like video playback and drag-and-drop that have
been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft
Silverlight, and Google Gears.
Browser Support
The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support
many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5
functionality.
The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones
all have excellent support for HTML5.
New Features
HTML5 introduces a number of new elements and attributes that can help you in building
modern websites. Here is a set of some of the most prominent features introduced in
HTML5.
New Semantic Elements: These are like <header>, <footer>, and <section>.
Forms 2.0: Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
Server-Sent Events: HTML5 introduces events which flow from web server to the
web browsers and they are called Server-Sent Events (SSE).
Canvas: This supports a two-dimensional drawing surface that you can program
with JavaScript.
Audio & Video: You can embed audio or video on your webpages without resorting
to third-party plugins.
Geolocation: Now visitors can choose to share their physical location with your
web application.
9
HTML5
Microdata: This lets you create your own vocabularies beyond HTML5 and extend
your web pages with custom semantics.
Drag and drop: Drag and drop the items from one location to another location on
the same webpage.
Backward Compatibility
HTML5 is designed, as much as possible, to be backward compatible with existing web
browsers. Its new features have been built on existing features and allow you to provide
fallback content for older browsers.
It is suggested to detect support for individual HTML5 features using a few lines of
JavaScript.
If you are not familiar with any previous version of HTML, I would recommend that you go
through our HTML Tutorial before exploring the features of HTML5.
10
2. HTML5 Syntax
HTML5
The HTML 5 language has a "custom" HTML syntax that is compatible with HTML 4 and
XHTML1 documents published on the Web, but is not compatible with the more esoteric
SGML features of HTML 4.
HTML 5 does not have the same syntax rules as XHTML where we needed lower case tag
names, quoting our attributes, an attribute had to have a value and to close all empty
elements.
HTML5 comes with a lot of flexibility and it supports the following features
The DOCTYPE
DOCTYPEs in older versions of HTML were longer because the HTML language was SGML
based and therefore required a reference to a DTD.
HTML 5 authors would use simple syntax to specify DOCTYPE as follows:
<!DOCTYPE html>
The above syntax is case-insensitive.
Character Encoding
HTML 5 authors can use simple syntax to specify Character Encoding as follows
<meta charset="UTF-8">
The above syntax is case-insensitive.
HTML5
HTML5 Elements
HTML5 elements are marked up using start tags and end tags. Tags are delimited using
angle brackets with the tag name in between.
The difference between start tags and end tags is that the latter includes a slash before
the tag name.
Following is the example of an HTML5 element
<p>...</p>
HTML5 tag names are case insensitive and may be written in all uppercase or mixed case,
although the most common convention is to stick with lowercase.
Most of the elements contain some content like <p>...</p> contains a paragraph. Some
elements, however, are forbidden from containing any content at all and these are known
as void elements. For example, br, hr, link, meta, etc.
Here is a complete list of HTML5 Elements.
HTML5 Attributes
Elements may contain attributes that are used to set various properties of an element.
Some attributes are defined globally and can be used on any element, while others are
defined for specific elements only. All attributes have a name and a value and look like as
shown below in the example.
Following is the example of an HTML5 attribute which illustrates how to mark up a div
element with an attribute named class using a value of "example"
<div class="example">...</div>
Attributes may only be specified within start tags and must never be used in end tags.
HTML5 attributes are case insensitive and may be written in all uppercase or mixed case,
although the most common convention is to stick with lowercase.
Here is a complete list of HTML5 Attributes.
12
HTML5
HTML5 Document
The following tags have been introduced for better structure
aside: This tag represents a piece of content that is only slightly related to the rest
of the page.
footer: This tag represents a footer for a section and can contain information about
the author, copyright information, et cetera.
nav: This tag represents a section of the document intended for navigation.
figure: This tag can be used to associate a caption together with some embedded
content, such as a graphic or video.
The markup for an HTML 5 document would look like the following
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header>...</header>
<nav>...</nav>
<article>
<section>
...
</section>
</article>
13
HTML5
<aside>...</aside>
<footer>...</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header role="banner">
<h1>HTML5 Document Structure Example</h1>
<p>This page should be tried in safari, chrome or Mozila.</p>
</header>
<nav>
<ul>
<li><a href="http://www.tutorialspoint.com/html">HTML
Tutorial</a></li>
<li><a href="http://www.tutorialspoint.com/css">CSS
Tutorial</a></li>
<li><a href="http://www.tutorialspoint.com/javascript">JavaScript
Tutorial</a></li>
</ul>
</nav>
<article>
<section>
<p>Once article can have multiple sections</p>
14
HTML5
</section>
</article>
<aside>
<p>This is
</aside>
<footer>
<p>Created by <a href="http://tutorialspoint.com/">Tutorials
Point</a></p>
</footer>
</body>
</html>
It will produce the following result
15
3. HTML5 Attributes
HTML5
As explained in the previous chapter, elements may contain attributes that are used to set
various properties of an element.
Some attributes are defined globally and can be used on any element, while others are
defined for specific elements only. All attributes have a name and a value and look like as
shown below in the example.
Following is the example of an HTML5 attributes which illustrates how to mark up a div
element with an attribute named class using a value of "example"
<div class="example">...</div>
Attributes may only be specified within start tags and must never be used in end tags.
HTML5 attributes are case insensitive and may be written in all uppercase or mixed case,
although the most common convention is to stick with lowercase.
Standard Attributes
The attributes listed below are supported by almost all the HTML 5 tags.
Attribute
Options
Function
accesskey
User Defined
align
background
URL
bgcolor
numeric,
hexidecimal, RGB
values
class
User Defined
contenteditable
true, false
contextmenu
Menu id
data-XXXX
User Defined
draggable
true,false, auto
16
HTML5
height
Numeric Value
hidden
hidden
id
User Defined
item
List of elements
itemprop
List of items
spellcheck
true, false
style
subject
User define id
tabindex
Tab number
title
User Defined
valign
width
Numeric Value
For a complete list of HTML5 Tags and related attributes, please check our reference
to HTML5 Tags.
Custom Attributes
A new feature being introduced in HTML 5 is the addition of custom data attributes.
A custom data attribute starts with data- and would be named based on your requirement.
Here is a simple example
<div class="example" data-subject="physics" data-level="complex">
...
</div>
The above code will be perfectly valid HTML5 with two custom attributes called datasubject and data-level. You would be able to get the values of these attributes using
JavaScript APIs or CSS in similar way as you get for standard attributes.
17
4. HTML5 Events
HTML5
When users visit your website, they perform various activities such as clicking on text and
images and links, hover over defined elements, etc. These are examples of what JavaScript
calls events.
We can write our event handlers in Javascript or VBscript and you can specify these event
handlers as a value of event tag attribute. The HTML5 specification defines various event
attributes as listed below
We can use the following set of attributes to trigger any javascript or vbscript code
given as value, when there is any event that takes place for any HTML5 element.
We would cover element-specific events while discussing those elements in detail in
subsequent chapters.
Attribute
Value
Description
offline
script
onabort
script
onafterprint
script
onbeforeonload
script
onbeforeprint
script
onblur
script
oncanplay
script
oncanplaythrough
script
onchange
script
onclick
script
oncontextmenu
script
ondblclick
script
ondrag
script
ondragend
script
ondragenter
script
ondragleave
script
ondragover
script
18
HTML5
ondragstart
script
ondrop
script
ondurationchange
script
onemptied
script
onended
script
onerror
script
onfocus
script
onformchange
script
onforminput
script
onhaschange
script
oninput
script
oninvalid
script
onkeydown
script
onkeypress
script
onkeyup
script
onload
script
onloadeddata
script
onloadedmetadata
script
onloadstart
script
onmessage
script
onmousedown
script
onmousemove
script
onmouseout
script
onmouseover
script
onmouseup
script
onmousewheel
script
onoffline
script
onoine
script
19
HTML5
ononline
script
onpagehide
script
onpageshow
script
onpause
script
onplay
script
onplaying
script
onpopstate
script
onprogress
script
onratechange
script
onreadystatechange
script
onredo
script
onresize
script
onscroll
script
onseeked
script
onseeking
script
onselect
script
onstalled
script
onstorage
script
onsubmit
script
onsuspend
script
ontimeupdate
script
onundo
script
onunload
script
onvolumechange
script
onwaiting
script
20
HTML5
Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and
attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and free
us from a great deal of tedious scripting and styling that was required in HTML4.
Description
text
password
checkbox
radio
An enumerated value.
submit
file
image
hidden
select
textarea
button
A free form of button which can initiates any event related to button.
Following is the simple example of using labels, radio buttons, and submit buttons
...
<form action="http://example.com/cgiscript.pl" method="post">
<p>
HTML5
Description
datetime
A date and time (year, month, day, hour, minute, second, fractions of a
second) encoded according to ISO 8601 with the time zone set to UTC.
datetimelocal
A date and time (year, month, day, hour, minute, second, fractions of a
second) encoded according to ISO 8601, with no time zone information.
date
month
week
time
number
It accepts only numerical value. The step attribute specifies the precision,
defaulting to 1.
range
The range type is used for input fields that should contain a value from a
range of numbers.
It accepts only email value. This type is used for input fields that should
contain an e-mail address. If you try to submit a simple text, it forces to
enter only email address in email@example.com format.
url
It accepts only URL value. This type is used for input fields that should
contain a URL address. If you try to submit a simple text, it forces to enter
22
HTML5
HTML5 - datetime
A date and time (year, month, day, hour, minute, second, fractions of a second) encoded
according to ISO 8601 with the time zone set to UTC.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Output
23
HTML5
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Output
HTML5 date
A date (year, month, day) encoded according to ISO 8601.
Example
<!DOCTYPE HTML>
<html>
<body>
HTML5
Output
HTML5 month
A date consisting of a year and a month encoded according to ISO 8601.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
25
HTML5
Output
HTML5 - week
A date consisting of a year and a week number encoded according to ISO 8601.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Output
26
HTML5
HTML5 time
A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Output
HTML5 number
It accepts only numerical value. The step attribute specifies the precision, defaulting to 1.
Example
<!DOCTYPE HTML>
<html>
<body>
27
HTML5
Select Number : <input type = "number" min = "0" max = "10" step "1"
value = "5" name = "newinput" />
<input type = "submit" value = "submit" />
</form>
</body>
</html>
Output
HTML5 range
The range type is used for input fields that should contain a value from a range of numbers.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
28
HTML5
Output
HTML5 - email
It accepts only email value. This type is used for input fields that should contain an e-mail
address. If you try to submit a simple text, it forces to enter only email address in
email@example.com format.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Output
29
HTML5
HTML5 URL
It accepts only URL value. This type is used for input fields that should contain a URL
address. If you try to submit a simple text, it forces to enter only URL address either
in http://www.example.com format or in http://example.com format.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Output
30
HTML5
<html>
<script type="text/javascript">
function showResult()
{
x = document.forms["myform"]["newinput"].value;
document.forms["myform"]["result"].value=x;
}
</script>
<body>
onclick="showResult();" />
<output name="result"/>
</form>
</body>
</html>
It will produce the following result
HTML5
<body>
</body>
</html>
This will produce the following result
HTML5
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
33
HTML5
34
6. HTML5 SVG
HTML5
SVG stands for Scalable Vector Graphics and it is a language for describing 2D-graphics
and graphical applications in XML and the XML is then rendered by an SVG viewer.
SVG is mostly useful for vector type diagrams like Pie charts, Two-dimensional graphs in
an X,Y coordinate system etc.
SVG became a W3C Recommendation 14. January 2003 and you can check latest version
of SVG specification at SVG Specification.
Click the "I'll be careful, I promise!" button on the warning message that appears
(and make sure you adhere to it!).
Type html5.enable into the filter bar at the top of the page.
Now your Firefox HTML5 parser should be enabled and you should be able to experiment
with the following examples.
35
HTML5
<body>
<h2>HTML5 SVG Circle</h2>
<svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
<circle id="redcircle" cx="50" cy="50" r="50" fill="red" />
</svg>
</body>
</html>
This would produce the following result in HTML5 enabled latest version of Firefox.
<head>
<title>SVG</title>
36
HTML5
<body>
<h2>HTML5 SVG Rectangle</h2>
<svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
<rect id="redrect" width="300" height="100" fill="red" />
</svg>
</body>
</html>
This would produce the following result in HTML5 enabled latest version of Firefox.
<head>
<title>SVG</title>
<meta charset="utf-8" />
</head>
<body>
37
HTML5
</svg>
</body>
</html>
You can use the style attribute which allows you to set additional style information like
stroke and fill colors, width of the stroke, etc.
This would produce the following result in HTML5 enabled latest version of Firefox.
<body>
<h2>HTML5 SVG Ellipse</h2>
<svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="100" cy="50" rx="100" ry="50" fill="red" />
</svg>
</body>
</html>
38
HTML5
This would produce the following result in HTML5 enabled latest version of Firefox.
</svg>
</body>
</html>
This would produce the following result in HTML5 enabled latest version of Firefox.
39
HTML5
<head>
<title>SVG</title>
<meta charset="utf-8" />
</head>
<body>
</body>
</html>
This would produce the following result in HTML5 enabled latest version of Firefox.
40
HTML5
<!DOCTYPE html>
<html>
<head>
<title>SVG</title>
<meta charset="utf-8" />
</head>
<body>
<h2>HTML5 SVG Gradient Ellipse</h2>
<svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<radialGradient id="gradient" cx="50%" cy="50%" r="50%" fx="50%"
fy="50%">
<stop offset="0%" style="stop-color:rgb(200,200,200); stopopacity:0"/>
<stop offset="100%" style="stop-color:rgb(0,0,255); stopopacity:1"/>
</radialGradient>
</defs>
<ellipse cx="100" cy="50" rx="100" ry="50" style="fill:url(#gradient)" />
</svg>
</body>
</html>
This would produce the following result in HTML5 enabled latest version of Firefox.
41
HTML5
<head>
<style>
#svgelem{
position: relative;
left: 50%;
-webkit-transform: translateX(-40%);
-ms-transform: translateX(-40%);
transform: translateX(-40%);
}
</style>
<title>SVG</title>
<meta charset="utf-8" />
</head>
<body>
<h2 align="center">HTML5 SVG Star</h2>
<svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
<polygon points="100,10 40,180 190,60 10,60 160,180" fill="red"/>
</svg>
</body>
</html>
This would produce the following result in HTML5 enabled latest version of Firefox.
42
HTML5
43
7. HTML5 MathML
HTML5
The HTML syntax of HTML5 allows for MathML elements to be used inside a document
using <math>...</math> tags.
Most of the web browsers can display MathML tags. If your browser does not support
MathML, then I would suggest you to use latest version of Firefox.
MathML Examples
Following is a valid HTML5 document with MathML
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Pythagorean theorem</title>
</head>
<body>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
<msup><mi>a</mi><mn>2</mn></msup>
<mo>+</mo>
<msup><mi>b</mi><mn>2</mn></msup>
<mo>=</mo>
<msup><mi>c</mi><mn>2</mn></msup>
</mrow>
</math>
</body>
</html>
44
HTML5
<head>
<meta charset="UTF-8">
<title>MathML Examples</title>
</head>
<body>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
<mrow>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
<mo>+</mo>
<mrow>
45
HTML5
<mn>4</mn>
<mo></mo>
<mi>x</mi>
</mrow>
<mo>+</mo>
<mn>4</mn>
</mrow>
<mo>=</mo>
<mn>0</mn>
</mrow>
</math>
</body>
</html>
This would produce the following result. If you are not able to see proper result like x2 +
4x + 4 = 0, then use Firefox 3.5 or higher version.
This will produce the following result
46
HTML5
<head>
<meta charset="UTF-8">
<title>MathML Examples</title>
</head>
<body>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>A</mi>
<mo>=</mo>
<mtable>
<mtr>
<mtd><mi>x</mi></mtd>
<mtd><mi>y</mi></mtd>
</mtr>
<mtr>
<mtd><mi>z</mi></mtd>
<mtd><mi>w</mi></mtd>
</mtr>
</mtable>
</mfenced>
</mrow>
</math>
</body>
</html>
47
HTML5
This would produce the following result. If you are not able to see proper result, then use
Firefox 3.5 or higher version.
48
HTML5
HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing structured
data on the client side and to overcome following drawbacks.
Cookies are included with every HTTP request, thereby slowing down your web
application by transmitting the same data.
Cookies are included with every HTTP request, thereby sending data unencrypted
over the internet.
Cookies are limited to about 4 KB of data. Not enough to store required data.
The two storages are session storage and local storage and they would be used to
handle different situations.
The latest versions of pretty much every browser supports HTML5 Storage including
Internet Explorer.
Session Storage
The Session Storage is designed for scenarios where the user is carrying out a single
transaction, but could be carrying out multiple transactions in different windows at the
same time.
Example
For example, if a user buying plane tickets in two different windows, using the same site.
If the site used cookies to keep track of which ticket the user was buying, then as the user
clicked from page to page in both windows, the ticket currently being purchased would
"leak" from one window to the other, potentially causing the user to buy two tickets for
the same flight without really noticing.
HTML5 introduces the sessionStorage attribute which would be used by the sites to add
data to the session storage, and it will be accessible to any page from the same site opened
in that window, i.e., session and as soon as you close the window, the session would be
lost.
Following is the code which would set a session variable and access that variable
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
49
HTML5
if( sessionStorage.hits ){
sessionStorage.hits = Number(sessionStorage.hits) +1;
}else{
sessionStorage.hits = 1;
}
document.write("Total Hits :" + sessionStorage.hits );
</script>
</body>
</html>
This will produce the following result
Local Storage
The Local Storage is designed for storage that spans multiple windows, and lasts beyond
the current session. In particular, Web applications may wish to store megabytes of user
data, such as entire user-authored documents or a user's mailbox, on the client side for
performance reasons.
Again, cookies do not handle this case well, because they are transmitted with every
request.
Example
HTML5 introduces the localStorage attribute which would be used to access a page's local
storage area without no time limit and this local storage will be available whenever you
would use that page.
50
HTML5
Following is the code which would set a local storage variable and access that variable
every time this page is accessed, even next time, when you open the window
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
}else{
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
</body>
</html>
This will produce the following result
HTML5
The Session Storage Data would be deleted by the browsers immediately after the session
gets terminated.
To clear a local storage setting you would need to call localStorage.remove('key');
where 'key' is the key of the value you want to remove. If you want to clear all settings,
you need to call localStorage.clear() method.
Following is the code which would clear complete local storage
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
localStorage.clear();
// Reset number of hits.
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
}else{
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
</body>
</html>
This will produce the following result
52
HTML5
53
HTML5
The Web SQL Database API isn't actually part of the HTML5 specification but it is a separate
specification which introduces a set of APIs to manipulate client-side databases using SQL.
I'm assuming you are a great web developer and if that is the case then no doubt, you
would be well aware of SQL and RDBMS concepts. If you still want to have a session with
SQL then, you can go through our SQL Tutorial.
Web SQL Database will work in latest version of Safari, Chrome and Opera.
openDatabase: This method creates the database object either using existing
database or creating new one.
Opening Database
The openDatabase method takes care of opening a database if it already exists, this
method will create it if it already does not exist.
To create and open a database, use the following code
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
The above method took the following five parameters
Database name
Version number
Text description
Size of database
Creation callback
The last and 5th argument, creation callback will be called if the database is being created.
Without this feature, however, the databases are still being created on the fly and correctly
versioned.
54
HTML5
Executing queries
To execute a query you use the database.transaction() function. This function needs a
single argument, which is a function that takes care of actually executing the query as
follows
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
});
The above query will create a table called LOGS in 'mydb' database.
INSERT Operation
To create enteries into the table we add simple SQL query in the above example as follows
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id,log) VALUES (?, ?'), [e_id, e_log];
});
Here e_id and e_log are external variables, and executeSql maps each item in the array
argument to the "?"s.
READ Operation
To read already existing records we use a callback to capture the results as follows
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
55
HTML5
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML +=
msg;
}, null);
});
Final Example
So finally, let us keep this example in a full-fledged HTML5 document as follows and try to
run it with Safari browser.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML =
msg;
});
56
HTML5
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML +=
msg;
msg;
}
}, null);
});
</script>
</head>
<body>
<div id="status" name="status">Status Message</div>
</body>
</html>
This will produce the following result
57
10.
HTML5
Conventional web applications generate events which are dispatched to the web server.
For example, a simple click on a link requests a new page from the server.
The type of events which are flowing from web browser to the web server may be called
client-sent events.
Along with HTML5, WHATWG Web Applications 1.0 introduces events which flow from web
server to the web browsers and they are called Server-Sent Events (SSE). Using SSE you
can push DOM events continuously from your web server to the visitor's browser.
The event streaming approach opens a persistent connection to the server, sending data
to the client when new information is available, eliminating the need for continuous polling.
Server-sent events standardize how we stream data from the server to the client.
<head>
<script type="text/javascript">
/* Define event handling logic here */
</script>
</head>
<body>
<div id="sse">
<eventsource src="/cgi-bin/ticker.cgi" />
</div>
<div id="ticker">
58
HTML5
<TIME>
</div>
</body>
</html>
while(true){
print "Event: server-time\n";
$time = localtime();
print "Data: $time\n";
sleep(5);
}
59
HTML5
<head>
<script type="text/javascript">
document.getElementsByTagName("eventsource")[0].addEventListener("server-time",
eventHandler, false);
function eventHandler(event)
{
// Alert time sent by the server
document.querySelector('#ticker').innerHTML = event.data;
}
</script>
</head>
<body>
<div id="sse">
<eventsource src="/cgi-bin/ticker.cgi" />
</div>
</body>
</html>
Before testing Server-Sent events, I would suggest that you make sure your web browser
supports this concept.
60
11.
HTML5 WebSockets
HTML5
WebSocket Attributes
Following are the attribute of WebSocket object. Assuming we created Socket object as
mentioned above
Attribute
Description
The readonly attribute readyState represents the state of
the connection. It can have the following values:
Socket.readyState
Socket.bufferedAmount
61
HTML5
WebSocket Events
Following are the events associated with WebSocket object. Assuming we created Socket
object as mentioned above
Event
Event Handler
Description
open
Socket.onopen
message
Socket.onmessage
error
Socket.onerror
close
Socket.onclose
WebSocket Methods
Following are the methods associated with WebSocket object. Assuming we created Socket
object as mentioned above
Method
Description
Socket.send()
Socket.close()
WebSocket Example
A WebSocket is a standard bidirectional TCP socket between the client and the server. The
socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP
handshake. After the handshake, either side can send data.
HTML5
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
63
HTML5
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>
Install pywebsocket
Before you test above client program, you need a server which supports WebSocket.
Download mod_pywebsocket-x.x.x.tar.gz from pywebsocket which aims to provide a Web
Socket extension for Apache HTTP Server and install it following these steps.
64
12.
HTML5 Canvas
HTML5
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using
JavaScript. It can be used to draw graphs, make photo compositions or do simple (and
not so simple) animations.
Here
is
a
simple
<canvas>
element
which
has
only
two
specific
attributes width and height plus all the core HTML5 attributes like id, name and class,
etc.
<canvas id="mycanvas" width="100" height="100"></canvas>
You can easily find that <canvas> element in the DOM using getElementById() method as
follows
var canvas
= document.getElementById("mycanvas");
<body>
<canvas id="mycanvas" width="100" height="100"></canvas>
</body>
</html>
This will produce the following result
65
HTML5
= document.getElementById("mycanvas");
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
Browser Support
The latest versions of Firefox, Safari, Chrome and Opera all support for HTML5 Canvas but
IE8 does not support canvas natively.
You can use ExplorerCanvas to have canvas support through Internet Explorer. You just
need to include this JavaScript as follows:
<!--[if IE]><script src="excanvas.js"></script><![endif]-->
Description
Drawing Rectangles
Drawing Paths
Drawing Lines
Drawing Bezier
66
HTML5
Drawing Quadratic
Using Images
Create Gradients
Canvas States
Canvas Translation
Canvas Rotation
Canvas Scaling
Canvas Transform
Canvas Composition
Canvas Animation
67
HTML5
Here x and y specify the position on the canvas (relative to the origin) of the top-left corner
of the rectangle and width and height are width and height of the rectangle.
Example
Following is a simple example which makes use of above mentioned methods to draw a
nice rectangle.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// Draw shapes
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
68
HTML5
}
}
</script>
</head>
</html>
The above code would draw the following rectangle
This method marks the current subpath as closed, and starts a new subpath
with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
69
HTML5
stroke()
This method strokes the subpaths with the current stroke style.
arc(x, y, radius, startAngle, endAngle, anticlockwise)
Adds points to the subpath such that the arc described by the circumference
of the circle described by the arguments, starting at the given start angle and
ending at the given end angle, going in the given direction, is added to the
path, connected to the previous point by a straight line.
Example
Following is a simple example which makes use of above mentioned methods to draw a
shape.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true);
// Outer circle
ctx.moveTo(110,75);
70
HTML5
ctx.arc(75,75,35,0,Math.PI,false);
// Mouth
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true);
// Left eye
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true);
// Right eye
ctx.stroke();
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
</html>
It will produce the following output:
HTML5
beginPath()
This method marks the current subpath as closed, and starts a new subpath
with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
lineTo(x, y)
This method adds the given point to the current subpath, connected to the
previous one by a straight line.
Example
Following is a simple example which makes use of the above-mentioned methods to draw
a triangle.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
HTML5
if (canvas.getContext){
// Stroked triangle
ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);
ctx.closePath();
ctx.stroke();
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
73
HTML5
Line Properties
There are several properties which allow us to style lines.
Sr.No.
This property returns the current line width and can be set, to change the
line width.
lineCap [ = value ]
This property returns the current line cap style and can be set, to change the
line cap style. The possible line cap styles are butt, round, and square
lineJoin [ = value ]
This property returns the current line join style and can be set, to change the
line join style. The possible line join styles are bevel, round, and miter.
miterLimit [ = value ]
This property returns the current miter limit ratio and can be set, to change
the miter limit ratio.
Example
Following is a simple example which makes use of lineWidth property to draw lines of
different width.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
74
HTML5
<script type="text/javascript">
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
for (i=0;i<10;i++){
ctx.lineWidth = 1+i;
ctx.beginPath();
ctx.moveTo(5+i*14,5);
ctx.lineTo(5+i*14,140);
ctx.stroke();
}
}
else
{
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
HTML5
This method marks the current subpath as closed, and starts a new subpath
with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
This method adds the given point to the current path, connected to the
previous one by a cubic Bezier curve with the given control points.
The x and y parameters in bezierCurveTo() method are the coordinates of the end point.
cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the
coordinates of the second control point.
Example
Following is a simple example which makes use of above mentioned methods to draw a
Bezier curves.
<!DOCTYPE HTML>
<html>
76
HTML5
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
ctx.beginPath();
ctx.moveTo(75,40);
ctx.bezierCurveTo(75,37,70,25,50,25);
ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
ctx.bezierCurveTo(20,80,40,102,75,120);
ctx.bezierCurveTo(110,102,130,80,130,62.5);
ctx.bezierCurveTo(130,62.5,130,25,100,25);
ctx.bezierCurveTo(85,25,75,37,75,40);
ctx.fill();
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
77
HTML5
}
}
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
The above example would draw the following shape:
5
6
This method marks the current subpath as closed, and starts a new subpath
with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
quadraticCurveTo(cpx, cpy, x, y)
78
HTML5
This method adds the given point to the current path, connected to the
previous one by a quadratic Bezier curve with the given control point.
The x and y parameters in quadraticCurveTo() method are the coordinates of the end
point. cpx and cpy are the coordinates of the control point.
Example
Following is a simple example which makes use of above mentioned methods to draw a
Quadratic curves.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// Draw shapes
79
HTML5
ctx.beginPath();
ctx.moveTo(75,25);
ctx.quadraticCurveTo(25,25,25,62.5);
ctx.quadraticCurveTo(25,100,50,100);
ctx.quadraticCurveTo(50,120,30,125);
ctx.quadraticCurveTo(60,120,65,100);
ctx.quadraticCurveTo(125,100,125,62.5);
ctx.quadraticCurveTo(125,25,75,25);
ctx.stroke();
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
</html>
The above example would draw the following shape
80
HTML5
This method marks the current subpath as closed, and starts a new subpath
with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
drawImage(image, dx, dy)
This method draws the given image onto the canvas. Here image is a
reference to an image or canvas object. x and y form the coordinate on the
target canvas where our image should be placed.
Example
Following is a simple example which makes use of above mentioned methods to import an
image.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function drawShape(){
HTML5
// Draw shapes
var img = new Image();
img.src = '/images/backdrop.jpg';
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
}
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
It will produce the following result
82
HTML5
<style>
#test {
83
HTML5
width:100px;
height:100px;
margin:0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(1, '#fff');
// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
84
HTML5
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<style>
#test {
width:100px;
height:100px;
margin:0px auto;
}
85
HTML5
</style>
<script type="text/javascript">
function drawShape(){
// Create gradients
var radgrad = ctx.createRadialGradient(45,45,10,52,50,30);
radgrad.addColorStop(0, '#A7D30C');
radgrad.addColorStop(0.9, '#019F62');
radgrad.addColorStop(1, 'rgba(1,159,98,0)');
// draw shapes
ctx.fillStyle = radgrad4;
ctx.fillRect(0,0,150,150);
86
HTML5
ctx.fillStyle = radgrad3;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad2;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad;
ctx.fillRect(0,0,150,150);
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
87
HTML5
Sr.No.
This attribute represents the color or style to use inside the shapes.
strokeStyle
This attribute represents the color or style to use for the lines around shapes
By default, the stroke and fill color are set to black which is CSS color value #000000.
A fillStyle Example
Following is a simple example which makes use of the above-mentioned fillStyle attribute
to create a nice pattern.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// Create a pattern
for (var i=0;i<7;i++){
88
HTML5
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
</html>
The above example would produce the following result
A strokeStyle Example
Following is a simple example which makes use of the above-mentioned fillStyle attribute
to create another nice pattern.
<!DOCTYPE HTML>
<html>
89
HTML5
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// Create a pattern
for (var i=0;i<10;i++){
HTML5
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
This property returns the current font settings and can be set, to change the
font.
textAlign [ = value ]
This property returns the current text alignment settings and can be set, to
change the alignment. The possible values are start, end, left,
right, andcenter.
textBaseline [ = value ]
This property returns the current baseline alignment settings and can be set,
to change the baseline alignment. The possible values are top, hanging,
middle , alphabetic, ideographic and bottom
fillText(text, x, y [, maxWidth ] )
This property fills the given text at the given position indicated by the given
coordinates x and y.
91
HTML5
strokeText(text, x, y [, maxWidth ] )
5
This property strokes the given text at the given position indicated by the
given coordinates x and y.
Example
Following is a simple example which makes use of above mentioned attributes to draw a
text
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
ctx.fillStyle
= '#00F';
ctx.font
HTML5
ctx.textBaseline = 'Top';
ctx.fillText
ctx.font
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
</html>
The above example would produce the following result
93
HTML5
createPattern(image, repetition)
This method will use image to create the pattern. The second argument could
be a string with one of the following values: repeat, repeat-x, repeaty, andno-repeat. If the empty string or null is specified, repeat will. be
assumed
Example
Following is a simple example which makes use of above mentioned method to create a
nice pattern.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
HTML5
img.src = 'images/pattern.jpg';
img.onload = function(){
// create pattern
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0,150,150);
}
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
Assuming we have following pattern images/pattern.jpg.
Create Shadows
HTML5 canvas provides capabilities to create nice shadows around the drawings. All
drawing operations are affected by the four global shadow attributes.
95
HTML5
Sr.No.
This property returns the current shadow color and can be set, to change the
shadow color.
shadowOffsetX [ = value ]
This property returns the current shadow offset X and can be set, to change
the shadow offset X.
shadowOffsetY [ = value ]
This property returns the current shadow offset Y and can be set, change the
shadow offset Y.
shadowBlur [ = value ]
This property returns the current level of blur applied to shadows and can be
set, to change the blur level.
Example
Following is a simple example which makes use of above mentioned attributes to draw a
shadow.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
HTML5
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
</html>
HTML5
shadowBlur,
textBaseline.
shadowColor,
globalCompositeOperation,
font,
textAlign,
Canvas states are stored on a stack every time the save method is called, and the last
saved state is returned from the stack every time the restore method is called.
Sr.No.
This method pops the top state on the stack, restoring the context to that
state.
Example
Following is a simple example which makes use of above mentioned methods to show how
the restore is called, to restore the original state and the last rectangle is once again drawn
in black.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
HTML5
if (canvas.getContext){
//
ctx.fillRect(0,0,150,150);
//
ctx.save();
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
99
HTML5
}
}
</script>
</head>
</html>
The above example would produce the following result
Example
Following is a simple example which makes use of above method to draw various
Spirographs
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
100
HTML5
height:100px;
margin:0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
for (i=0;i<3;i++) {
for (j=0;j<3;j++) {
ctx.save();
ctx.strokeStyle = "#FF0066";
ctx.translate(50+j*100,50+i*100);
drawSpirograph(ctx,10*(j+3)/(j+2),-2*(i+3)/(i+1),10);
ctx.restore();
}
}
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
function drawSpirograph(ctx,R,r,O){
var x1 = R-O;
101
HTML5
var y1 = 0;
var i
= 1;
ctx.beginPath();
ctx.moveTo(x1,y1);
do {
if (i>20000) break;
var x2 = (R+r)*Math.cos(i*Math.PI/72) (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
var y2 = (R+r)*Math.sin(i*Math.PI/72) (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
ctx.lineTo(x2,y2);
x1 = x2;
y1 = y2;
i++;
} while (x2 != R-O && y2 != 0 );
ctx.stroke();
}
</script>
</head>
102
HTML5
Example
Following is a simple example which we are running two loops where first loop determines
the number of rings, and the second determines the number of dots drawn in each ring.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
103
HTML5
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
ctx.fill();
}
ctx.restore();
}
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
104
HTML5
</html>
The above example would produce the following result
Example
Following is a simple example which uses spirograph function to draw nine shapes with
different scaling factors.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function drawShape(){
105
HTML5
ctx.strokeStyle = "#fc0";
ctx.lineWidth = 1.5;
ctx.fillRect(0,0,300,300);
// Uniform scaling
ctx.save()
ctx.translate(50,50);
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(0.75,0.75);
drawSpirograph(ctx,22,6,5);
ctx.translate(133.333,0);
ctx.scale(0.75,0.75);
drawSpirograph(ctx,22,6,5);
ctx.restore();
ctx.translate(100,0);
ctx.scale(1,0.75);
106
HTML5
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(1,0.75);
drawSpirograph(ctx,22,6,5);
ctx.restore();
ctx.translate(133.333,0);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.translate(177.777,0);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.restore();
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
function drawSpirograph(ctx,R,r,O){
var x1 = R-O;
var y1 = 0;
var i
= 1;
ctx.beginPath();
ctx.moveTo(x1,y1);
107
HTML5
do {
if (i>20000) break;
var x2 = (R+r)*Math.cos(i*Math.PI/72) (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
var y2 = (R+r)*Math.sin(i*Math.PI/72) (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
ctx.lineTo(x2,y2);
x1 = x2;
y1 = y2;
i++;
}
<body onload="drawShape();">
<canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>
This method changes the transformation matrix to apply the matrix given by
the arguments.
setTransform(m11, m12, m21, m22, dx, dy)
This method changes the transformation matrix to the matrix given by the
arguments .
108
HTML5
The transform(m11, m12, m21, m22, dx, dy) method must multiply the current
transformation matrix with the matrix described by
m11
m21
dx
m12
m22
dy
The setTransform(m11, m12, m21, m22, dx, dy) method must reset the current transform
to the identity matrix, and then invoke the transform(m11, m12, m21, m22, dx,
dy) method with the same arguments.
Example
Following is a simple example which makes use of transform() and setTransform()
methods
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function drawShape(){
ctx.translate(200, 200);
var c = 0;
HTML5
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload="drawShape();">
<canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>
The above example would produce the following result
110
HTML5
Description
source-over
This is the default setting and draws new shapes on top of the
existing canvas content.
source-in
The new shape is drawn only where both the new shape and the
destination canvas overlap. Everything else is made transparent.
source-out
source-atop
lighter
xor
destination-over
destination-in
The existing canvas content is kept where both the new shape
and existing canvas content overlap. Everything else is made
transparent.
destination-out
destination-atop
darker
Example
Following is a simple example which makes use of globalCompositeOperation attribute to
create all possible compositions
<!DOCTYPE HTML>
<html>
<head>
111
HTML5
<script type="text/javascript">
var compositeTypes = [
'source-over','source-in','source-out','source-atop',
'destination-over','destination-in','destination-out',
'destination-atop','lighter','darker','copy','xor'
];
function drawShape(){
for (i=0;i<compositeTypes.length;i++){
var label = document.createTextNode(compositeTypes[i]);
document.getElementById('lab'+i).appendChild(label);
var ctx = document.getElementById('tut'+i).getContext('2d');
// draw rectangle
ctx.fillStyle = "#FF3366";
ctx.fillRect(15,15,70,70);
// draw circle
ctx.fillStyle = "#0066FF";
ctx.beginPath();
ctx.arc(75,75,35,0,Math.PI*2,true);
ctx.fill();
}
}
</script>
</head>
<body onload="drawShape();">
<table border="1" align="center">
<tr>
<td><canvas id="tut0" width="125" height="125"></canvas><br/>
<label id="lab0"></label>
</td>
HTML5
<label id="lab1"></label>
</td>
<tr>
<td><canvas id="tut3" width="125" height="125"></canvas><br/>
<label id="lab3"></label>
</td>
<tr>
<td><canvas id="tut6" width="125" height="125"></canvas><br/>
<label id="lab6"></label>
</td>
<tr>
<td><canvas id="tut9" width="125" height="125"></canvas><br/>
113
HTML5
<label id="lab9"></label>
</td>
</body>
</html>
HTML5
115
HTML5
setTimeout(callback, time);
2
This method executes the supplied code only once after a given time
milliseconds.
Example
Following is a simple example which would rotate a small image repeatedly
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var pattern= new Image();
function animate(){
pattern.src = '/html5/images/pattern.jpg';
setInterval(drawShape, 100);
}
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save();
ctx.translate(150,150);
HTML5
ctx.restore();
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload="animate();">
<canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>
The above example would produce the following result
117
13.
HTML5
HTML5 features include native audio and video support without the need for Flash.
The HTML5 <audio> and <video> tags make it simple to add media to a website. You
need to set src attribute to identify the media source and include a controls attribute so
the user can play and pause the media.
Embedding Video
Here is the simplest form of embedding a video file in your webpage:
<video src="foo.mp4"
Ogg: Ogg files with Thedora video codec and Vorbis audio codec.
mpeg4: MPEG4 files with H.264 video codec and AAC audio codec.
You can use <source> tag to specify media along with media type and many other
attributes. A video element allows multiple source elements and browser will use the first
recognized format:
<!DOCTYPE HTML>
<html>
<body>
<video
118
HTML5
Description
autoplay
autobuffer
controls
If this attribute is present, it will allow the user to control video playback,
including volume, seeking, and pause/resume playback.
height
This attribute specifies the height of the video's display area, in CSS
pixels.
loop
This Boolean attribute if specified, will allow video automatically seek back
to the start after reaching at the end.
preload
This attribute specifies that the video will be loaded at page load, and
ready to run. Ignored if autoplay is present.
poster
src
The URL of the video to embed. This is optional; you may instead use the
<source> element within the video block to specify the video to embed
width
This attribute specifies the width of the video's display area, in CSS pixels.
119
HTML5
Embedding Audio
HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML
document as follows.
<audio src="foo.wav" controls autoplay>
Your browser does not support the <audio> element.
</audio>
The current HTML5 draft specification does not specify which audio formats browsers
should support in the audio tag. But most commonly used audio formats are ogg,
mp3 and wav.
You can use <source> tag to specify media along with media type and many other
attributes. An audio element allows multiple source elements and browser will use the first
recognized format:
<!DOCTYPE HTML>
<html>
<body>
<audio controls autoplay>
<source src="/html5/audio.ogg" type="audio/ogg" />
<source src="/html5/audio.wav" type="audio/wav" />
Your browser does not support the <audio> element.
</audio>
</body>
</html>
This will produce the following result
120
HTML5
Description
autoplay
autobuffer
controls
If this attribute is present, it will allow the user to control audio playback,
including volume, seeking, and pause/resume playback.
loop
This Boolean attribute if specified, will allow audio automatically seek back
to the start after reaching at the end.
preload
This attribute specifies that the audio will be loaded at page load, and
ready to run. Ignored if autoplay is present.
src
The URL of the audio to embed. This is optional; you may instead use the
<source> element within the video block to specify the video to embed
Description
abort
canplay
This event is generated when enough data is available that the media
can be played.
ended
error
loadeddata
This event is generated when the first frame of the media has finished
loading.
loadstart
pause
play
progress
ratechange
121
HTML5
seeked
seeking
suspend
volumechange
waiting
value="Play"/>
</form>
</body>
</html>
122
HTML5
123
14.
HTML5 Geolocation
HTML5
HTML5 Geolocation API lets you share your location with your favorite web sites. A
JavaScript can capture your latitude and longitude and can be sent to backend web server
and do fancy location-aware things like finding local businesses or showing your location
on a map.
Today most of the browsers and mobile devices support Geolocation API. The geolocation
APIs work with a new property of the global navigator object ie. Geolocation object which
can be created as follows:
var geolocation = navigator.geolocation;
The geolocation object is a service object that allows widgets to retrieve information about
the geographic location of the device.
Geolocation Methods
The geolocation object provides the following methods:
Method
Description
getCurrentPosition()
watchPosition()
clearWatch()
Example
Following is a sample code to use any of the above method:
function getLocation() {
var geolocation = navigator.geolocation;
geolocation.getCurrentPosition(showLocation, errorHandler);
}
Here showLocation and errorHandler are callback methods which would be used to get
actual position as explained in next section and to handle errors if there is any.
124
HTML5
Syntax
Here is the syntax of this method
getCurrentPosition(showLocation, ErrorHandler, options);
Parameters
Here is the detail of parameters
showLocation This specifies the callback method that retrieves the location
information. This method is called asynchronously with an object corresponding to
the Position object which stores the returned location information.
options This optional parameter specifies a set of options for retrieving the
location information. You can specify (a) Accuracy of the returned location
information (b) Timeout for retrieving the location information and (c) Use of
cached location information.
Return value
The getCurrentPosition method does not return a value.
Example
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
125
HTML5
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation,
errorHandler, options);
}
else{
alert("Sorry, browser does not support geolocation!");
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="getLocation();" value="Get Location"/>
</form>
</body>
</html>
126
HTML5
Syntax
Here is the syntax of this method
watchPosition(showLocation, ErrorHandler, options);
Parameters
Here is the detail of parameters
showLocation This specifies the callback method that retrieves the location
information. This method is called asynchronously with an object corresponding to
the Position object which stores the returned location information.
options This optional parameter specifies a set of options for retrieving the
location information. You can specify (a) Accuracy of the returned location
information (b) Timeout for retrieving the location information and (c) Use of
cached location information.
Return value
The watchPosition method returns a unique transaction ID (number) associated with the
asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving
location updates.
Example
<!DOCTYPE HTML>
<head>
<html>
<script type="text/javascript">
var watchID;
var geoLoc;
127
HTML5
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
function getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
else{
alert("Sorry, browser does not support geolocation!");
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="getLocationUpdate();" value="Watch
Update"/>
</form>
128
HTML5
</body>
</html>
This will produce the following result -
Syntax
Here is the syntax of this method
clearWatch(watchId);
Parameters
Here is the detail of parameters
watchId This specifies the unique ID of the watchPosition call to cancel. The ID
is returned by the watchPosition call.
Return value
The clearWatch method does not return a value.
Example
<!DOCTYPE HTML>
<html>
<head>
129
HTML5
<script type="text/javascript">
var watchID;
var geoLoc;
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
function getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
else{
alert("Sorry, browser does not support geolocation!");
}
}
function stopWatch(){
geoLoc.clearWatch(watchID);
}
</script>
130
HTML5
</head>
<body>
<form>
<input type="button" onclick="getLocationUpdate();" value="Watch
Update"/>
<input type="button" onclick="stopWatch();" value="Stop Watch"/>
</form>
</body>
</html>
This will produce the following result
Location Properties
Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the
callback method that retrieves the location information. These methods are called
asynchronously with an object Position which stores the complete location information.
The Position object specifies the current geographic location of the device. The location
is expressed as a set of geographic coordinates together with information about heading
and speed.
The following table describes the properties of the Position object. For the optional
properties if the system cannot provide a value, the value of the property is set to null.
Property
coords
Type
objects
Description
Specifies the geographic location of the device.
The location is expressed as a set of geographic
coordinates together with information about
heading and speed.
131
HTML5
coords.latitude
Number
coords.longitude
Number
coords.altitude
Number
coords.accuracy
Number
coords.altitudeAccuracy
Number
coords.heading
Number
coords.speed
Number
timestamp
date
Example
Following is a sample code which makes use of Position object. Here showLocation method
is a callback method:
function showLocation( position ) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
...
}
Handling Errors
Geolocation is complicated, and it is very much required to catch any error and handle it
gracefully.
The geolocations methods getCurrentPosition() and watchPosition() make use of an error
handler callback method which gives PositionError object. This object has following two
properties:
Property
Type
Description
code
Number
message
String
132
HTML5
The following table describes the possible error codes returned in the PositionError object.
Code
Constant
Description
UNKNOWN_ERROR
PERMISSION_DENIED
POSITION_UNAVAILABLE
TIMEOUT
Example
Following is a sample code which makes use of PositionError object. Here errorHandler
method is a callback method:
function errorHandler( err ) {
if (err.code == 1) {
// access is denied
}
...
}
Position Options
Following is the actual syntax of getCurrentPosition() method:
getCurrentPosition(callback, ErrorCallback, options)
Here third argument is the PositionOptions object which specifies a set of options for
retrieving the geographic location of the device.
Following are the options which can be specified as third argument:
Property
Type
Description
enableHighAccuracy
Boolean
timeout
Number
133
HTML5
maximumAge
Number
Example
Following is a sample code which shows how to use above mentioned methods:
function getLocation() {
var geolocation = navigator.geolocation;
geolocation.getCurrentPosition(showLocation, errorHandler,
{maximumAge: 75000});
}
134
15.
HTML5 Microdata
HTML5
Example
To add a property to an item, the itemprop attribute is used on one of the item's
descendants.
Here there are two items, each of which has the property "name":
<html>
<body>
<div itemscope>
<p>My name is <span itemprop="name">Zara</span>.</p>
</div>
<div itemscope>
<p>My name is <span itemprop="name">Nuha</span>.</p>
</div>
</body>
</html>
It will produce the following result
Properties generally have values that are strings but it can have following data types:
135
HTML5
Global Attributes
Microdata introduces five global attributes which would be available for any element to use
and give context for machines about your data.
Attribute
Description
itemscope
itemtype
This attribute is a valid URL which defines the item and provides
the context for the properties.
itemid
itemprop
itemref
Properties Datatypes
Properties generally have values that are strings as mentioned in above example but they
can also have values that are URLs. Following example has one property, "image", whose
value is a URL:
<div itemscope>
<img itemprop="image" src="tp-logo.gif" alt="TutorialsPoint">
</div>
Properties can also have values that are dates, times, or dates and times. This is achieved
using the time element and its datetime attribute.
<html>
<body>
<div itemscope>
My birthday is:
<time itemprop="birthday" datetime="1971-05-08">
Aug 5th 1971
</time>
</div>
</body>
</html>
136
HTML5
Properties can also themselves be groups of name-value pairs, by putting the itemscope
attribute on the element that declares the property.
HTML5
<html>
<body>
<div itemscope>
<section itemscope itemtype="http://data-vocabulary.org/Person">
<h1 itemprop="name">Gopal K Varma</h1>
<p>
<img itemprop="photo"
src="http://www.tutorialspoint.com/green/images/logo.png">
</p>
</body>
</html>
It will produce the following result
Google supports microdata as part of their Rich Snippets program. When Google's web
crawler parses your page and finds microdata properties that conform to the http://datavocabulary.org/Person vocabulary, it parses out those properties and stores them
alongside the rest of the page data.
You
can
test
above
example
using Rich
http://www.tutorialspoint.com/html5/microdata.htm
Snippets
Testing
Tool using
For further development on Microdata you can always refer to HTML5 Microdata.
138
16.
HTML5
Drag and Drop (DnD) is powerful User Interface concept which makes it easy to copy,
reorder and deletion of items with the help of mouse clicks. This allows the user to click
and hold the mouse button down over an element, drag it to another location, and release
the mouse button to drop the element there.
To achieve drag and drop functionality with traditional HTML4, developers would either
have to either have to use complex JavaScript programming or other JavaScript
frameworks like jQuery etc.
Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD support to
the browser making it much easier to code up.
HTML 5 DnD is supported by all the major browsers like Chrome, Firefox 3.5 and Safari 4
etc.
Description
dragstart
dragenter
Fired when the mouse is first moved over the target element while a
drag is occurring. A listener for this event should indicate whether a
drop is allowed over this location. If there are no listeners, or the
listeners perform no operations, then a drop is not allowed by default.
dragover
dragleave
This event is fired when the mouse leaves an element while a drag is
occurring. Listeners should remove any highlighting or insertion
markers used for drop feedback.
drag
Fires every time the mouse is moved while the object is being
dragged.
drop
The drop event is fired on the element where the drop was occurred
at the end of the drag operation. A listener would be responsible for
retrieving the data being dragged and inserting it at the drop location.
dragend
Fires when the user releases the mouse button while dragging an
object.
Note: Note that only drag events are fired; mouse events such as mousemove are not
fired during a drag operation.
139
HTML5
dataTransfer.effectAllowed [ = value ]
2
dataTransfer.types
3
Returns a DOMStringList listing the formats that were set in the dragstart
event. In addition, if any files are being dragged, then one of the types will be
the string "Files".
dataTransfer.clearData ( [ format ] )
7
8
Removes the data of the specified formats. Removes all data if the argument is
omitted.
dataTransfer.setData(format, data)
Adds the specified data.
data = dataTransfer.getData(format)
Returns the specified data. If there is no such data, returns the empty string.
dataTransfer.files
Returns a FileList of the files being dragged, if any.
dataTransfer.setDragImage(element, x, y)
140
HTML5
Uses the given element to update the drag feedback, replacing any previously
specified feedback.
dataTransfer.addElement(element)
9
Adds the given element to the list of elements used to render the drag
feedback.
If you want to drag an element, you need to set the draggable attribute to true
for that element.
Set an event listener for dragstart that stores the data being dragged.
The event listener dragstart will set the allowed effects (copy, move, link, or some
combination).
HTML5
<body>
<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to drag the purple box around.</div>
The dragenter event, which is used to determine whether or not the drop target
is to accept the drop. If the drop is to be accepted, then this event has to be
canceled.
Finally, the drop event, which allows the actual drop to be performed.
HTML5
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#boxA, #boxB {
float:left;padding:10px;margin:10px;-moz-user-select:none;
}
#boxA { background-color: #6633FF; width:75px; height:75px;
HTML5
ondragstart="return dragStart(event)">
<p>Drag Me</p>
</div>
<div id="boxB" ondragenter="return dragEnter(event)"
ondrop="return dragDrop(event)"
ondragover="return dragOver(event)">Dustbin</div>
</center>
</body>
</html>
This will produce the following result
144
17.
HTML5
145
HTML5
When you click Big Loop button it displays following result in Firefox:
146
HTML5
function sayHello(){
alert("Hello sir...." );
}
</script>
</head>
<body>
<input type="button" onclick="sayHello();" value="Say Hello"/>
</body>
147
HTML5
</html>
Following is the content of bigLoop.js file. This makes use of postMessage() API to pass
the communication back to main page:
for (var i = 0; i <= 1000000000; i += 1){
var j = i;
}
postMessage(j);
This will produce the following result
Handling Errors
The following shows an example of an error handling function in a Web Worker JavaScript
file that logs errors to the console. With error handling code, above example would become
as following:
<!DOCTYPE HTML>
<html>
<head>
<title>Big for loop</title>
<script>
var worker = new Worker('bigLoop.js');
148
HTML5
function sayHello(){
alert("Hello sir...." );
}
</script>
</head>
<body>
<input type="button" onclick="sayHello();" value="Say Hello"/>
</body>
</html>
HTML5
</html>
This will produce the following result
150
18.
HTML5 IndexedDB
HTML5
The indexeddb is a new HTML5 concept to store the data inside user's browser. indexeddb
is more power than local storage and useful for applications that requires to store large
amount of the data. These applications can run more efficiency and load faster.
Features
IndexedDB
Before enter into an indexeddb, we need to add some prefixes of implementation as shown
below
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB;
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
HTML5
request.onsuccess = function(event) {
alert("Prasad has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nPrasad is already exist in your database! ");
}
}
Retrieving Data
We can retrieve the data from the data base using with get()
function read() {
var transaction = db.transaction(["employee"]);
var objectStore = transaction.objectStore("employee");
var request = objectStore.get("00-03");
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
if(request.result) {
alert("Name: " + request.result.name + ", Age: " + request.result.age
+ ", Email: " + request.result.email);
}
152
HTML5
else {
alert("Kenny couldn't be found in your database!");
}
};
}
Using with get(), we can store the data in object instead of that we can store the data in
cursor and we can retrieve the data from cursor
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " + cursor.value.name + ",
Age: " + cursor.value.age + ", Email: " + cursor.value.email);
cursor.continue();
}
else {
alert("No more entries!");
}
};
}
request.onsuccess = function(event) {
alert("prasad entry has been removed from your database.");
};
}
153
HTML5
HTML Code
To show all the data we need to use onClick event as shown below code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
The final code should be as:
<!DOCTYPE html>
<html>
<head>
if (!window.indexedDB) {
154
HTML5
const employeeData = [
{ id: "00-01", name: "gopal", age: 35, email:
"gopal@tutorialspoint.com" },
{ id: "00-02", name: "prasad", age: 32, email:
"prasad@tutorialspoint.com" }
];
var db;
var request = window.indexedDB.open("newDatabase", 1);
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("employee", {keyPath:
"id"});
function read() {
var transaction = db.transaction(["employee"]);
var objectStore = transaction.objectStore("employee");
var request = objectStore.get("00-03");
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
155
HTML5
};
request.onsuccess = function(event) {
// Do something with the request.result!
if(request.result) {
alert("Name: " + request.result.name + ", Age: " +
request.result.age + ", Email: " + request.result.email);
}
else {
alert("Kenny couldn't be found in your database!");
}
};
}
function readAll() {
var objectStore =
db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " +
cursor.value.name + ", Age: " + cursor.value.age + ", Email: " +
cursor.value.email);
cursor.continue();
}
else {
alert("No more entries!");
}
};
}
function add() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
156
HTML5
request.onsuccess = function(event) {
alert("Kenny has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nKenny is aready exist in your
database! ");
}
}
function remove() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.delete("00-03");
request.onsuccess = function(event) {
alert("Kenny's entry has been removed from your database.");
};
}
</script>
</head>
<body>
</body>
</html>
157
HTML5
158
19.
HTML5
Web Messaging is the way for documents to separates browsing context to share the data
without Dom. It overrides the cross domain communication problem in different domains,
protocols or ports.
For example, you want to send the data from your page to ad container which is placed at
iframe or voice-versa, in this scenario, Browser throws a security exception. With web
messaging we can pass the data across as a message event.
Message Event
Message events fires Cross-document messaging, channel messaging, server-sent events
and web sockets.it has described by Message Event interface.
Attributes
Attributes
Description
data
origin
lastEventId
source
ports
Examples
Sending message from iframe to button
var iframe = document.querySelector('iframe');
var button = document.querySelector('button');
HTML5
iframe.contentWindow.postMessage('The message to
send.','https://www.tutorialspoint.com);
}
button.addEventListener('click',clickHandler,false);
Receiving a cross-document message in the receiving document
var messageEventHandler = function(event){
// check that the origin is one we want.
if(event.origin == 'https://www.tutorialspoint.com'){
alert(event.data);
}
}
window.addEventListener('message', messageEventHandler,false);
Channel messaging
Two-way communication between the browsing contexts is called channel messaging. It
is useful for communication across multiple origins.
In this scenario, we are sending the data from one iframe to another iframe. Here we are
invoking the data in function and passing the data to DOM.
var loadHandler = function(){
var mc, portMessageHandler;
mc = new MessageChannel();
window.parent.postMessage('documentAHasLoaded','http://foo.example',[mc.port2])
;
portMessageHandler = function(portMsgEvent){
alert( portMsgEvent.data );
}
HTML5
mc.port1.start();
}
window.addEventListener('DOMContentLoaded', loadHandler, false);
Above code, it is taking the data from port 2, now it will pass the data to second iframe
var loadHandler = function(){
var iframes, messageHandler;
iframes = window.frames;
messageHandler = function(messageEvent){
if( messageEvent.ports.length > 0 ){
// transfer the port to iframe[1]
iframes[1].postMessage('portopen','http://foo.example',messageEvent.ports);
}
}
window.addEventListener('message',messageHandler,false);
}
window.addEventListener('DOMContentLoaded',loadHandler,false);
Now second document handles the data by using the portMsgHandler function.
var loadHandler(){
// Define our message handler function
var messageHandler = function(messageEvent){
161
20.
HTML5 CORS
HTML5
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS
requests.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
162
HTML5
Description
onloadstart
onprogress
onabort
onerror
onload
ontimeout
onloadend
xhr.onerror = function() {
console.log('There was an error!');
};
if ("withCredentials" in xhr) {
HTML5
else {
// CORS not supported.
xhr = null;
}
return xhr;
}
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
164
HTML5
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
165
21.
HTML5
Web RTC introduced by World Wide Web Consortium (W3C). That supports browser-tobrowser applications for voice calling, video chat, and P2P file sharing.
If you want to try out? web RTC available for Chrome, Opera, and Firefox. A good place to
start is the simple video chat application at here. Web RTC implements three API's as
shown below
MediaStream
The MediaStream represents synchronized streams of media, For an example, Click on
HTML5 Video player in HTML5 demo section or else click here.
The above example contains stream.getAudioTracks() and stream.VideoTracks(). If there
is no audio tracks, it returns an empty array and it will check video stream,if webcam
connected, stream.getVideoTracks() returns an array of one MediaStreamTrack
representing the stream from the webcam. A simple example is chat applications, a chat
application gets stream from web camera, rear camera, microphone.
Sample code of MediaStream
function gotStream(stream) {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
Screen capture
It's also possible in Chrome browser with mediaStreamSource and it requires HTTPS. This
feature is not yet available in opera. Sample demo is available at here
166
HTML5
// get the local stream, show it in the local video element and send it
navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
selfView.src = URL.createObjectURL(stream);
pc.addStream(stream);
if (isCaller)
pc.createOffer(gotDescription);
else
pc.createAnswer(pc.remoteDescription, gotDescription);
function gotDescription(desc) {
pc.setLocalDescription(desc);
signalingChannel.send(JSON.stringify({ "sdp": desc }));
167
HTML5
}
});
}
if (signal.sdp)
pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
else
pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
};
168