Learn Basic HTML5

Transcription

Learn Basic HTML5
i
Table of Contents
Table of Contents.................................................................................................i
Intro ................................................................................................................... v
What’s New?.................................................................................................... viii
HTML5 Page Structure ....................................................................................... ix

Minimum HTML5 Document .................................................................. ix

Basic Syntax Improvements in HTML5 .................................................... ix

HTML5 Document................................................................................... xi
New Attributes in <input> Element ..................................................................... 1
The ‘type’ Attribute ............................................................................................ 2
The ‘placeholder’ Attribute ................................................................................ 3
The ‘autofocus’ Attribute ................................................................................... 3
The ‘required’ Attribute ..................................................................................... 4
New Elements in HTML5 ..................................................................................... 5
New Media Elements ......................................................................................... 6

The <canvas> Element ............................................................................ 6

The <audio> Element .............................................................................. 8

The <video> Element ............................................................................ 10

The <source> Element .......................................................................... 13

The <embed> Element.......................................................................... 14

The <track> Element ............................................................................. 15
New Form Elements ......................................................................................... 17
i|Page- LetsDnD.com
ii

The <datalist> Element ......................................................................... 17

The <keygen> Element ......................................................................... 19

The <output> Element .......................................................................... 21
New Semantic/Structural Elements ................................................................. 22

The <article> Element ........................................................................... 22

The <aside> Element ............................................................................ 23

The <section> Element ......................................................................... 24

The <header> Element ......................................................................... 25

The <nav> Element ............................................................................... 25

The <footer> Element ........................................................................... 26

The <bdi> Element ................................................................................ 27

The <command> Element ..................................................................... 27

The <details> Element .......................................................................... 28

The <summary> Element ...................................................................... 29

The <dialog> Element ........................................................................... 29

The <figure> Element ........................................................................... 30

The <figcaption> Element ..................................................................... 30

The <mark> Element............................................................................. 31

The <meter> Element ........................................................................... 31

The <progress> Element ....................................................................... 32

The <ruby> Element ............................................................................. 33

The <rt> Element .................................................................................. 33

The <rp> Element ................................................................................. 34

The <time> Element ............................................................................. 34

The <wbr> Element .............................................................................. 35
ii | P a g e - L e t s D n D . c o m
iii
Drag and Drop .................................................................................................. 37
Geo Location ..................................................................................................... 43
Storages of HTML5 ............................................................................................ 48
The localStorage Object ................................................................................... 49
The sessionStorage Object ............................................................................... 50
Offline Web Browsing ....................................................................................... 51
Application Cache ............................................................................................ 52
Manifest File .................................................................................................... 53
Server Sent Event.............................................................................................. 56
About Author .................................................................................................... 59
Thank You ......................................................................................................... 60
iii | P a g e - L e t s D n D . c o m
iv
Learn Basic HTML5 - Second Edition
By Sandeep Likhar
Copyright © 2014 Let’s Design n Develop
All rights reserved. No part of this book may be used or reproduced in any
manner whatsoever without permission from the author.
2nd Edition - 2014
iv | P a g e - L e t s D n D . c o m
- Intro -
“I’m The Future of Your Web
Browser”
vi
Introduction
HTML5 is the newest hyper text markup language for websites from the World
Wide Web Consortium (W3C). The first draft was made public in 2008, but not
much happened until 2011. In 2011, HTML5 was released and people started
writing about it and using it, but the support in different browsers was still poor.
The World Wide Web Consortium (W3C) is the main international
standards organization for the World Wide Web. For more information
visit http://www.w3.org/
Today all major browsers offer HTML5 support, therefore the newest HTML
technology can be used at its best today.
Answer :
vi | P a g e - L e t s D n D . c o m
Popular Web Browsers
Indentify any of these?
From L to R - Chrome,
Firefox, Internet Explorer,
Opera, Safari
Question: Can You
vii
Introduction
HTML5 works with CSS3 and is still in development. W3C plans to release a stable
version next year, but it still looks like this is a long shot. Since its release, HTML5
has been in continuous development, with the W3C adding more and more
impressive features, therefore it seems quite unlikely that HTML5′s development
will end soon, which is not necessarily a bad thing.
HTML5 is the successor of HTML 4.01, released for the first time in 1999. The
internet has changed significantly since 1999 and it seemed like the creation of
HTML5 was necessary. The new markup language was developed based on preset standards:
 New features should be based on HTML, CSS, DOM, and JavaScript.
 The need for external plugins (like Flash) needs to be reduced.
 Error handling should be easier than in previous versions.
 Scripting has to be replaced by more markup.
 HTML5 should be device-independent.
 The development process should be visible to the public.
vii | P a g e - L e t s D n D . c o m
viii
Introduction
What’s New?
HTML5 is not yet an official standard, and no browsers have full HTML5 support.
But all major browsers (Safari, Chrome, Firefox, Opera, Internet Explorer)
continue to add new HTML5 features to their latest versions.
HTML5 was created to make the coding process easier and more logical. You will
see a bit later that many syntaxes are now deprecated and soon to be kicked out
through the back door.
The following tags from HTML 4.01 are now removed from HTML5, therefore
browsers do not offer support for them anymore. This means that it is a good idea
to go back to your HTML pages and check for them, as they might disrupt the
design in the latest browsers.
•
•
•
•
<acronym>
<applet>
<basefont>
<big>
•
•
•
•
<center>
<dir>
<font>
<frame>
•
•
•
•
<frameset>
<noframes>
<strike>
<tt>
The unique and impressive features comes with HTML5 are in the multimedia
department.
Many of the features comes with it have been created with the consideration that
users should be able to run heavy content on low-powered devices. The syntactic
features include the new <video>, <audio> and <canvas> elements, but also
integration of vector graphics content (what we knew before as being the <object>
tags). This means that multimedia and graphic content on the web will be handled
and executed easier and faster, without the need of plugins or APIs.
viii | P a g e - L e t s D n D . c o m
ix
Introduction
HTML5 Page Structure
 Minimum HTML5 Document
Below is a simple HTML5 document, with the minimum of required tags:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
Content of the document......
</body>
</html>
 Basic Syntax Improvements in HTML5
The <!Doctype> tag
In HTML5 there is only one <!doctype> declaration, and it is very simple:
<!DOCTYPE html>
The <script> tag
It's common practice to add a type attribute with a value of "text/javascript"
to script elements as follows:
<script type="text/javascript" src="scriptfile.js"></script>
HTML 5 removes extra information required and you can use simply
following syntax:
<script src="scriptfile.js"></script>
ix | P a g e - L e t s D n D . c o m
x
Introduction
The <link> tag
So far you were writing <link> as follows:
<link rel="stylesheet" type="text/css" href="stylefile.css">
HTML 5 removes extra information required and you can use simply following
syntax:
<link rel="stylesheet" href="stylefile.css">
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. Following is the simple example:
1. <div class="example" data-subject="physics" data-level="complex">
2. ...
3. </div>
The above will be perfectly valid HTML5 with two custom attributes called
data-subject 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.
As Chrome Browser supports most of the HTML5 elements, we
recommend you to use it for try out our examples. To download,
visit https://www.google.com/chrome/browser/
x|Page- LetsDnD.com
xi
Introduction
 HTML5 Document
Following is a sample HTML5 document which included new tags arrived with
HTML5.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>your web page title</title>
</head>
<body>
<header>
<nav>
<ul>
<li>Your Menu</li>
</ul>
</nav>
</header>
<section>
<article>
<header>
<h2>Article Title</h2>
<p>This is a my long paragraph. </p>
</header>
</article>
<article>
<header>
<h2>Article Title</h2>
<p>This is a my first long paragraph. </p>
</header>
<p>This is a my second long paragraph. </p>
</article>
</section>
<aside>
<h2>About Section</h2>
<p>This is a my first long paragraph in about us.</p>
</aside>
<footer>
<p>
Copyright 2014 Your name
</p>
</footer>
</body>
</html>
xi | P a g e - L e t s D n D . c o m
New Attributes in <input>
Element
“Creating Forms never been this
much easier”
2
New Attributes in <input> Element
The ‘type’ Attribute
HTML5 input elements introduced several new values for the type attribute.
These are listed below.
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.
datetime-local
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
A date (year, month, day) encoded according to ISO 8601.
month
A date consisting of a year and a month encoded according to ISO 8601.
week
A date consisting of a year and a week number encoded according to ISO 8601.
time
A time (hour, minute, seconds, and fractional seconds) encoded according to ISO 8601.
number
This accepts only numerical value. The step attribute specifies the precision, defaulting to 1.
2|Page- LetsDnD.com
3
New Attributes in <input> Element
range
The range type is used for input fields that should contain a value from a range of numbers.
email
This 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 protected] format.
url
This 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.
The ‘placeholder’ Attribute
HTML5 introduced a new attribute called placeholder. This attribute on <input>
and <textarea> elements provides a hint to the user of what can be entered in the
field. The placeholder text must not contain carriage returns or line-feeds.
Here is the simple syntax for placeholder attribute:
<input type="text" name="search" placeholder="search the web"/>
The ‘autofocus’ Attribute
This is a simple one-step pattern, easily programmed in JavaScript at the time of
document load, automatically focus one particular form field.
HTML5 introduced a new attribute called autofocus which would be used as
follows:
<input type="text" name="search" autofocus/>
3|Page- LetsDnD.com
4
New Attributes in <input> Element
The ‘required’ Attribute
Now you do not need to have JavaScript for client side validations like empty text
box would never be submitted because HTML5 introduced a new attribute called
required which would be used as follows and would insist to have a value:
<input type="text" name="search” required/>
4|Page- LetsDnD.com
New Elements in HTML5
“Super Cool HTML5…!!
You have Lot of New!!!”
6
New Elements in HTML5
New Media Elements
 The <canvas> Element
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.
The HTML5 Canvas element is an HTML tag similar to the <div>, <a>, or <table>
tag, with the exception that its contents are rendered with JavaScript. In order to
leverage the HTML5 Canvas, we'll need to place the canvas tag somewhere inside
the HTML document, access the canvas tag with JavaScript, create a context, and
then utilize the HTML5 Canvas API to draw visualizations.
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");
Let us see a simple example on using <canvas> element in HTML5 document.
<!DOCTYPE HTML>
<html>
<head>
<style>
#mycanvas {
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="100" height="100"></canvas>
</body>
</html>
6|Page- LetsDnD.com
7
New Elements in HTML5
You can create many shapes using canvas as example below:
The Rendering Context:
The <canvas> is initially blank, and to display something, a script first needs to
access the rendering context and draw on it.
When using canvas, it's important to understand the difference between the
canvas element and the canvas context, as often times people get these
confused. The canvas element is the actual DOM node that's embedded in the
HTML page. The canvas context is an object with properties and methods that
you can use to render graphics inside the canvas element. The context can be 2d
or 3d.
Each canvas element can only have one context. If we use the getContext()
method multiple times, it will return a reference to the same context object.
The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter,
the type of context 2d.
7|Page- LetsDnD.com
8
New Elements in HTML5
Following is the code to get required context along with a check if your browser
supports <canvas> element:
<body>
<canvas id="myCanvas" width="100" height="100"></canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
</script>
</body>
 The <audio> Element
The HTML <audio> element is used to represent sound content in documents.
Added as part of HTML5, it may contain several audio sources, represented using
the src attribute or the <source> element; the browser will choose the most
suitable one. Fallback content for browser not supporting the <audio> element
can be added too.
Before HTML5, the audio files could not be played on a web page without support
of third party plug-ins like Adobe Flash Player, Apple QuickTime Player etc. But
HTML5 defines a new element (<audio>) which provides native audio playback
support in the browser. The audio tag specifies a way to embed an audio file
within a web page.
HTML5 audio element is supported by latest versions of all web browsers. But
Internet Explorer 8 or earlier versions of Internet Explorer do not support audio
element.
8|Page- LetsDnD.com
9
New Elements in HTML5
Presently three audio file formats are supported by HTML5 audio element;
 .mp3
 .ogg
 .wav
HTML5 audio element example given below:
<audio controls="controls" loop="loop" autoplay="autoplay" preload="none">
<source src="song.mp3" type="audio/mpeg">
<source src="song.ogg" type="audio/ogg">
<source src="song.wav" type="audio/wav">
<p>Your browser does not support the audio element.</p>
</audio>
The text written between <audio> and </audio> tags is displayed if the browser
does not support audio element.
Attributes of Audio Element
controls
If this attribute is present, the browser will offer controls to allow the user to control audio
playback, including volume, seeking, and pause/resume playback.
src
The src attribute defines a valid source path of audio file.
loop
The loop attribute specifies whether the audio file should be repeatedly played.
9|Page- LetsDnD.com
10
New Elements in HTML5
autoplay
A Boolean attribute; if specified (even if the value is "false"!), the audio will automatically
begin to play back as soon as it can do so without stopping to finish loading the data.
buffered
An attribute you can read to determine which time ranges of the media have been
buffered. This attribute contains a Time-Ranges object.
preload
The preload attribute specifies when the audio file gets preloaded. Possible values are –
none / metadata / auto.
 none: hints that either the author thinks that the user won't need to consult that audio
or that the server wants to minimize its traffic; in others terms this hint indicates that
the audio should not be cached;
 metadata: hints that though the author thinks that the user won't need to consult that
audio, fetching the metadata (e.g. length) is reasonable;
 auto: hints that the user needs have priority; in others terms this hint indicated that, if
needed, the whole audio could be downloaded, even if the user is not expected to use
it;
 The <video> Element
The video tag is one of those HTML5 features that gets a lot of attention. Often
presented as an alternative to flash in the media, the video tag actually goes
beyond that. Although it's recently joined the rest of the ubiquitous HTML tags, its
capabilities and support across browsers have increased at an amazing speed.
The <video> element is brand new in HTML 5 and allows you to, get this, play a
movie in your website! The data of this element is supposed to be video but it
might also have audio or images associated with it.
10 | P a g e - L e t s D n D . c o m
11
New Elements in HTML5
The HTML 5 <video> tag accepts attributes that specify how the video should be
played. Attributes include preload, autoload, loop, play, pause and more.
Let’s take a look at each one in a little more detail.
autoplay
Tells the browser to start playing the video as soon as it is downloaded.
controls
Displays built-in controls that are native to the browser. Basic controls tend to include a
play/pause button, time counter, volume control, and time scrubber.
crossorigin
Either allows or prohibits the sharing of a video across other domains using CORS (CrossOrigin Resource Sharing).
height
Identifies the height of the video (if your height/width aren’t in the correct ratio, you
will see black banding above and below the video; it will not distort).
loop
Tells the browser to loop the video after playback has been completed.
mediagroup
Allows multiple media elements to be linked together by creating a media controller.
Therefore you can synchronize multiple videos or a video with audio.
muted
Allows the author to specify if the video should be muted when it begins to play.
11 | P a g e - L e t s D n D . c o m
12
New Elements in HTML5
poster
Identifies the location of a still image to use as a holding frame.
preload
Allows the author to inform the browser to start (or not start) downloading the video as
soon as the page is loaded. preload has replaced the autobuffer attribute. The autoplay
attribute can override the preload attribute if present. The available states are
 none: Tells the browser not to preload the file. The file will begin to load when the
user clicks Play.
 metadata: Tells the browser to only preload the metadata (dimensions, first frame,
duration, etc.). The rest of the file will begin to load when the user clicks Play.
 auto: Tells the browser to choose whether to download the entire file, nothing, or
only the metadata. This is the default state if preload isn’t specified.
src
Identifies the location of the video file (note that this is not required if a child source
element is present, which we’ll cover later).
width
Identifies the width of the video (if your height/width aren’t in the correct ratio, you will
see black banding above and below the video; it will not distort).
In order to implement HTML5 video cross browser, we need to be aware of three
container formats.
1. WebM
2. Ogg
3. MPEG-4
12 | P a g e - L e t s D n D . c o m
13
New Elements in HTML5
HTML5 video element example given below:
<video width="200" height="200" controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
<p>Your browser does not support video element</p>
</video>

The <source> Element
The <source> element is used to specify multiple media resources for <audio> and
<video> elements in HTML5. It is an empty element. It is commonly used to serve
the same media in multiple formats supported by different browsers.
The <source> tag basically replaces the single src attribute. Every HTML5 browser
will scan through these tags top to bottom, until it finds a video it can play. With a
combination of an MP4, ogg and a WebM video, you have nearly all HTML5
browsers covered (Firefox 3.x only supported the outdated OGG format, but that
browser version is almost gone now).
The HTML 5 <source> tag accepts attributes that specify how the video and audio
should be played. Attributes include src, type, media.
In the two examples below, the <video> and <audio> element is best example of
source element.
<audio controls="controls" loop="loop" autoplay="autoplay" preload="none">
<source src="song.mp3" type="audio/mpeg">
<source src="song.ogg" type="audio/ogg">
<p>Your browser does not support the audio element.</p>
</audio>
<video width="200" height="200" controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
<p>Your browser does not support video element.</p>
</video>
13 | P a g e - L e t s D n D . c o m
14
New Elements in HTML5
The type attribute is not required, but useful for increased performance. If it is not
set, all browsers will start downloading the first video to find out if it can play.
With the type set, Firefox and Opera recognize they should download the right
video instead of the other one.
 The <embed> Element
The <embed> is a non-standard but well-supported element that's used to embed
multimedia content, including media types that mightn't usually be natively
supported by the browser. It can also be used for embedding media types that are
supported, such as images in .jpg, .gif, or .png format.
The HTML <embed> tag is used for embedding another resource or interactive
content into the document. The <embed> element is an empty element and this
tag ending with the delimiter string ‘/>’.This tag has no closing tag like <embed/>.
This tag is used to insert nonstandard elements content, typically a multimedia
element that is not supported by HTML. You can use <embed> tag to add images,
audio or video etc or you can write anything in it.
The example below uses 4 different video formats. The HTML 5 <video> element
tries to play the video either in MP4, OGG, or WEBM format. If this fails, the code
"falls back" to try the <object> element. If this also fails, it "falls back" to the
<embed> element:
<video width="200" height="200" controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
<object data="video.mp4" width="200" height="200">
<embed src="video.swf" width="200" height="200" />
</object>
<p>Your browser does not support video element</p>
</video>
14 | P a g e - L e t s D n D . c o m
15
New Elements in HTML5

The <track> Element
The <track> element is used as a child of the media elements—<audio> and
<video>—and does not represent anything on its own. It lets you specify timed
text tracks (or time-based data).
The type of data that <track> adds to the media is set in the kind attribute, which
can take values of subtitles, captions, descriptions, chapters or metadata. The
element points to a source file containing timed text that the browser exposes
when the user requests additional data.
A media element cannot have more than one <track> with the same; kind
attribute, srclang attribute, and label attribute.
Each <track> element has an attribute for kind, which can be subtitles, captions,
descriptions, chapters or metadata. The track element src attribute points to a
text file that holds data for timed track cues, which can potentially be in any
format a browser can parse.
Let’s take a look at each one in a little more detail.
default
This attribute indicates that the track should be enabled unless the user's preferences
indicate that another track is more appropriate. This may only be used on
one track element per media element.
kind
How the text track is meant to be used. If omitted the default kind is subtitles. The
following keywords are allowed:

subtitles:
Subtitles provide translation of content that cannot be understood by the viewer. For
example dialogue or text that is not English in an English language film.
15 | P a g e - L e t s D n D . c o m
16
New Elements in HTML5
Subtitles may contain additional content, usually extra background information. For
example the text at the beginning of the Star Wars films, or the date, time, and location of
a scene.

captions:
Closed captions provide a transcription and possibly a translation of audio.
It may include important non-verbal information such as music cues or sound effects. It
may indicate the cue's source (e.g. music, text, character).
Suitable for users who are deaf or when the sound is muted.

descriptions:
Textual description of the video content.
Suitable for users who are blind or where the video cannot be seen.

chapters:
Chapter titles are intended to be used when the user is navigating the media resource.

metadata:
Tracks used by scripts. Not visible to the user.
label
A user-readable title of the text track which is used by the browser when listing available
text tracks.
src
Address of the track. Must be a valid URL. This attribute must be defined.
srclang
Language of the track text data. It must be a valid language tag. If the kind attribute is set
to subtitles, then srclang must be defined.
16 | P a g e - L e t s D n D . c o m
17
New Elements in HTML5
Html Code Example:
<video src="sample.ogv">
<track kind="captions" src="sampleCaptions.srt" srclang="en">
<track kind="descriptions" src="sampleDesciptions.srt" srclang="en">
<track kind="chapters" src="sampleChapters.srt" srclang="en">
<track kind="subtitles" src="sampleSubtitles_de.srt" srclang="de">
<track kind="subtitles" src="sampleSubtitles_en.srt" srclang="en">
<track kind="subtitles" src="sampleSubtitles_ja.srt" srclang="ja">
<track kind="subtitles" src="sampleSubtitles_oz.srt" srclang="oz">
<track kind="metadata" src="keyStage1.srt" srclang="en" label="Stage 1">
<track kind="metadata" src="keyStage2.srt" srclang="en" label="Stage 2">
<track kind="metadata" src="keyStage3.srt" srclang="en" label="Stage 3">
</video>
New Form Elements
 The <datalist> Element
You probably have experienced this kind of response somewhere on the Web:
when you are typing in an input form, a list of suggestions appears at the
bottom of the input.
Over the years, we rely on JavaScript to create such a function. Today, we are able
to do that with the new HTML5 <datalist> element. This HTML5 new element
allows us to store a list of options that will be shown as the users type in the
input.
The <datalist> can be linked to <input> element using a new HTML5 attribute, list.
We can use list in a few input types like text and search.The datalist contains
option elements much like the select element, though datalist itself is not an
independent control. Instead it is added or attached to an <input type="text"/>
element using the list attribute.
In the below code snippet we have a regular <input type="text" /> control with an
id and the new list attribute. This tells the browser to load the list of values or
suggestions from the datalist element with a corresponding id.
17 | P a g e - L e t s D n D . c o m
18
New Elements in HTML5
<label>Select your preferred code editor:</label>
<input type="text" id="txt_ide" list="ide" />
<datalist id="ide">
<option value="Brackets" />
<option value="Coda" />
<option value="Dreamweaver" />
<option value="Espresso" />
<option value="jEdit" />
<option value="Komodo Edit" />
<option value="Notepad++" />
<option value="Sublime Text 2" />
<option value="Taco HTML Edit" />
<option value="Textmate" />
<option value="Text Pad" />
<option value="TextWrangler" />
<option value="Visual Studio" />
<option value="VIM" />
<option value="XCode" />
</datalist>
Then comes the actual datalist element with the aforementioned id and a
collection of option elements. This is how the values are attached to the input
control.
When we run this in the browser, we will see a normal textbox, then when we
starting typing (or press the down arrow key, which works in Firefox and Chrome
but not in Opera) the complete or filtered list appears. As we type, only the
relevant options will be shown, much like how Google's Search box displays
suggestions. Be aware though, slight behavioral variations do exist from browser
to browser.
Example :
18 | P a g e - L e t s D n D . c o m
19
New Elements in HTML5
To hook the <datalist> to an <input> element, simply add list attribute and refer to
the id attribute, like so.
<input class="destination-list" type="text" placeholder="From:" list="city">
<input class="destination-list" type="text" placeholder="To:" list="city">
 The <keygen> Element
The HTML <keygen> element exists to facilitate generation of key material, and
submission of the public key as part of an HTML form. This mechanism is designed
for use with Web-based certificate management systems. It is expected that
the keygen element will be used in an HTML form along with other information
needed to construct a certificate request, and that the result of the process will
be a signed certificate.
Attributes
autofocus
This Boolean attribute lets you specify that the control should have input focus when the
page loads, unless the user overrides it, for example by typing in a different control. Only
one form element in a document can have the autofocus attribute, which is a Boolean.
challenge
A challenge string that is submitted along with the public key. Defaults to an empty string
if not specified.
disabled
This Boolean attribute indicates that the form control is not available for interaction.
19 | P a g e - L e t s D n D . c o m
20
New Elements in HTML5
form
The form element that this element is associated with (its form owner). The value of the
attribute must be an id of a <form> element in the same document. If this attribute is not
specified, this element must be a descendant of a <form> element. This attribute enables
you to place <keygen> elements anywhere within a document, not just as descendants
of their form elements.
keytype
The type of key generated. The default value is RSA.
name
The name of the control, which is submitted with the form data.
Html Code Example:
<form action="demo_keygen.asp" method="get">
Username: <input type="text" name="usr_name">
Encryption: <keygen name="security">
<input type="submit">
</form>
The keygen element is only valid within an HTML form. It will cause some sort of
selection to be presented to the user for selecting key size. The UI for the
selection may be a menu, radio buttons, or possibly something else. The browser
presents several possible key strengths. Currently, two strengths are offered, high
and medium. If the user's browser is configured to support cryptographic
hardware (e.g. "smart cards") the user may also be given a choice of where to
generate the key, i.e., in a smart card or in software and stored on disk.
When the submit button is pressed, a key pair of the selected size is generated.
The private key is encrypted and stored in the local key database.
20 | P a g e - L e t s D n D . c o m
21
New Elements in HTML5
 The <output> Element
Across the web, you’ll see a range of sites that feature calculators for working out
things like loan repayments, mortgage rates, tax, insurance, and more. Until now,
we’ve had no way of semantically marking up the result of those calculations.
The <output> element represents the result of a calculation. Example given below:
Along with the standard global attributes, <output> also accepts the following:
for
A space-separated list containing the IDs of the elements whose values went
into the calculation.
form
Associates the <output> element with its form owner. The value must be the
ID of a form in the same document. This allows you to place an <output>
element outside of the <form> with which it is associated.
name
The name of the element.
21 | P a g e - L e t s D n D . c o m
22
New Elements in HTML5
Html Code Example:
<form onsubmit="return false"
oninput="o.value = parseInt(a.value) + parseInt(b.value)">
<input name="a" type="number" step="any"> +
<input name="b" type="number" step="any"> =
<output name="o"></output>
</form>
New Semantic/Structural Elements
 The <article> Element
The HTML <article> Element represents a self-contained composition in a
document, page, application, or site, which is intended to be independently
distributable or reusable, e.g., in syndication. This could be a forum post, a
magazine or newspaper article, a blog entry, a user-submitted comment, an
interactive widget or gadget, or any other independent item of content.
From the above explanation, we can conclude that <article> element is exclusively
recommended to be used for structuring article, especially the article that most
likely we are going to syndicate, such as a blog post, page content or forum posts.
The following example shows how we structure blog-post content with <article>.
<article class="post">
<header>
<h1> This is Blog Post Title </h1>
<div class="post-meta">
<ul>
<li class="author">Author Name</li>
<li class="categories">Save in Categories</li>
</ul>
</div>
</header>
<div class="post-content">
Quisque id vehicula ante. Morbi id condimentum magna. non mollis
arcu vehicula eget. Nulla viverra lacinia nibh ut semper.
</div>
</article>
22 | P a g e - L e t s D n D . c o m
23
New Elements in HTML5
 The <aside> Element
The HTML <aside> Element represents a section of a page that consists of content
that is tangentially related to the content around it, which could be considered
separate from that content. Such sections are often represented as sidebars or as
inserts. They often contain side explanations, like a glossary definition; more
loosely related stuff, like advertisements; the biography of the author; or in webapplications, profile information or related blog links.
A sidebar in a webpage, containing associated links, profile information,
advertisement displays etc.. are good example of the kind of content you can
enclose in aside.
An example is a "pull quote" from a longer article. A pull quote (also known as a
lift-out quote or a call-out) is a quotation or edited excerpt from an article that is
placed in a larger typeface on the same page, serving to lead readers into an
article and to highlight a key topic.
Html Code Example:
<div style="font: 0.8em/ 1.2em Arial, Helvetica, Sans-Serif;">
<aside style="font-size:larger;font-style:italic;
color:green;float:right;width:35%;padding-left:5px;">
Proin accumsan, lectus id pretium pulvinar</aside>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Proin accumsan, lectus id pretium pulvinar, felis quam egestas magna,
neccursus.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Proin accumsan, lectus id pretium pulvinar, felis quam egestas magna,
neccursus.</p>
</div>
23 | P a g e - L e t s D n D . c o m
24
New Elements in HTML5
 The <section> Element
The HTML5 <section> element is not a replacement for a div. It’s easy to think it
should be, because all the other structural elements that were introduced in
HTML5 (header, footer, main etc.) replaced all the divs we used to use to denote
those areas of a page.
The HTML5 specification is clear about this
“The section element is not a generic container element. When an element is
needed only for styling purposes or as a convenience for scripting, authors are
encouraged to use the div element instead.”
If you’re wondering why it makes a difference, the answer is semantics. The div is
a semantically neutral element, the section element is not. The section element is
exposed through the browser’s accessibility API, and that information is picked up
by assistive technologies and communicated to users.
For example the Jaws screen reader announces “Region” each time it encounters
the section element. It announces “Region” rather than “Section” because the
section element maps to the role of region (and it’s the role that’s exposed via the
accessibility APIs).
<article>
<header>
<h1>
</header>
<section>
<h4>
<p>
</section>
<section>
<h4>
<p>
</section>
</article>
Welcome
</h1>
What We Do </h4>
We protect sharks...
News Items </h4>
Man eats shark... </p>
24 | P a g e - L e t s D n D . c o m
</p>
25
New Elements in HTML5
 The <header> Element
The HTML <header> tag represents a group of introductory or navigational aids.
Headers can contain headings, subheadings, version information, navigational
controls, etc.
The <header> element should be used as a container for introductory content or
set of navigational links.
You can have several <header> elements in one document.
The <header> element is intended to usually contain the section's heading (an
<h1>-<h6> element or an <hgroup> element), but this is not required. The
<header> element can also be used to wrap a section's table of contents, a search
form, or any relevant logos.
The <header> tag cannot be placed within a <footer>, <address> or another
<header> element.
<header>
<hgroup>
<h1>
<h2>
</h2>
</hgroup>
</header>
Talking Dogs
</h1>
Humans aren't the only talkers!
 The <nav> Element
One of the new elements for HTML 5 is the <nav> element which allows you to
group together links, resulting in more semantic markup and extra structure
which may help screen readers.
The nav element represents a section of a page that links to other pages or to
parts within the page: a section with navigation links. Not all groups of links on a
page need to be in a nav element only sections that consist of major navigation
25 | P a g e - L e t s D n D . c o m
26
New Elements in HTML5
blocks are appropriate for the nav element. In particular, it is common for footers
to have a list of links to various key parts of a site, but the footer element is more
appropriate in such cases, and no nav element is necessary for those links.
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
 The <footer> Element
The HTML <footer> tag is used for defining the footer of an HTML document or
section.
Footers usually contain information such as the author of the document,
copyright information, links to terms of use, privacy policy, etc.
Contact information within a <footer> tag should be marked up using
the <address> tag
Although footers are typically located at the bottom of a document, this is not
required
(although
it
cannot
be
placed
within
a <header> or
another <footer> element, and it cannot contain a <header> element).
A document/section can have more than one footer.
<footer>
<ul>
<li>copyright</li>
<li>sitemap</li>
<li>contact</li>
<li>to top</li>
</ul>
</footer>
26 | P a g e - L e t s D n D . c o m
27
New Elements in HTML5
 The <bdi> Element
The HTML <bdi> Element (or Bi-Directional Isolation Element) isolates a span of
text that might be formatted in a different direction from other text outside it.
This element is useful when embedding text with an unknown directionality, from
a database for example, inside text with a fixed directionality.
Though the same visual effect can be achieved using the CSS rule unicode-bidi:
isolate on a <span> or another text-formatting element, the semantic meaning is
only conveyed by the <bdi> element. Especially, browsers are allowed to ignore
CSS styling. In such a case, the text would still be correctly displayed using the
HTML element, but will become garbage when using the CSS styling to convey
semantic. The HTML <bdi> tag is used on a span of text that is to be isolated from
its surroundings for the purposes of bidirectional text formatting.
This can be useful when displaying right-to-left text (such as Arabic) inside left-toright text (such as English) when the text-direction is unknown.
The <bdi> element allows you to honor the correct directionality of text when this
is unknown (such as in the case with user-generated content).
<ol>
<li>User
<li>User
<li>User
<li>User
<li>User
</ol>
<bdi>homerjay</bdi>: 1601 posts</li>
<bdi>msimpson</bdi>: 335 posts</li>
<bdi>‫<إيان‬/bdi>: 195 posts</li>
<bdi>barts</bdi>: 6 posts</li>
<bdi>moe</bdi>: 2 posts</li>
 The <command> Element
The HTML <command> tag is used for specifying a command that the user can
invoke.
According to the HTML 5 specification:
27 | P a g e - L e t s D n D . c o m
28
New Elements in HTML5
A command is the abstraction behind menu items, buttons, and links. Once a
command is defined, other parts of the interface can refer to the same command,
allowing many access points to a single feature to share aspects such as the
disabled state.
The <command> tag was introduced in HTML 5.
<menu>
<command type="command" label="Save" onclick="save()">Save</command>
</menu>
Note: The command element is currently only supported in IE9.
 The <details> Element
The HTML <details> tag specifies additional details that the user can view or hide
on demand.
It can be used in conjunction with the HTML5 <summary> tag to provide a heading
that can be clicked on to expand/collapse the details as required.
Essentially, we can use <details> to create an accordion-like widget that the user
can toggle open and closed. Inside <details>, we can put any sort of content we
want.
The <details> tag was introduced in HTML 5.
<details open="open">
<p>
If your browser supports this element, it should allow you to
expand and collapse these details.
</p>
</details>
28 | P a g e - L e t s D n D . c o m
29
New Elements in HTML5
 The <summary> Element
The HTML <summary> tag specifies a summary/caption that can be used in
conjunction with the HTML5 <details> tag. This summary/caption can be clicked
on to expand/collapse the details as required.
The <summary> tag, if used, should be the first child of the <details> tag.
Essentially, we can use <details> to create an accordion-like widget that the user
can toggle open and closed. Inside <details>, we can put any sort of content we
want.
<details>
<summary>
Show/Hide me
</summary>
<p> Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas.
</p>
</details>
 The <dialog> Element
The <dialog> element originally entered the HTML5 scene as a way to markup
conversations but it was cut from the spec back in 2009. However now it’s back,
and it has a brand new role.
The new <dialog> element makes it really easy for developers to create popup
dialogs and modals for their web applications. Before now this required using a
JavaScript plugin. However popup dialogs have become so popular that the
Chrome team have decided to create a native implementation of this UI
component.
<dialog id="dialog">
<p>Hi, I'm a dialog!</p>
<button id="close">Okay</button>
</dialog>
Note: <dialog> has been dropped from the HTML5 specification.
29 | P a g e - L e t s D n D . c o m
30
New Elements in HTML5
 The <figure> Element
The HTML5 <figure> element is a new element created to allow designers to
associate images and other units of content with the main flow of content while
keeping them separate. A figure can be moved around in the content and even
away from the main content without affecting the meaning of the document as a
whole.
The HTML <figure> tag is used for annotating illustrations, diagrams, photos, code
listings, etc.
You can use the <figure> element to associate a caption together with some
embedded content, such as a graphic or video.
You can use the <figure> element in conjunction with the <figcaption> element to
provide a caption for the contents of your <figure> element.
<figure>
<img src="image.jpg" alt="The image tag" width="300" height="200">
</figure>
Note: Internet Explorer 8 and earlier versions do not support the <figure> tag.
 The <figcaption> Element
The HTML <figcaption> Element represents a caption or a legend associated with a
figure or an illustration described by the rest of the data of the <figure> element
which is its immediate ancestor which means <figcaption> can be the first or last
element inside a <figure> block. Also, the HTML Figcaption Element is optional; if
not provided, then the parent figure element will have no caption.
The most common use of the figure element is with images (with FIGCAPTION
providing captions for those images), but that isn't the only thing you can put in a
figure. You can also put in blocks of code, pull quotes, or any other content that is
related to the main content, but not critical to the flow.
30 | P a g e - L e t s D n D . c o m
31
New Elements in HTML5
<figure>
<img src="image.jpg" alt="The image tag" width="300" height="200">
<figcaption>
Fig1. - A view of the pulpit rock in Norway.
</figcaption>
</figure>
 The <mark> Element
The HTML <mark> tag is used for indicating text as marked or highlighted for
reference purposes, due to its relevance in another context.
It is important to understand the intended purpose of this tag. According to the
HTML 5 specification:
When used in a quotation or other block of text referred to from the prose, it
indicates a highlight that was not originally present but which has been added to
bring the reader's attention to a part of the text that might not have been
considered important by the original author when the block was originally
written, but which is now under previously unexpected scrutiny. When used in
the main prose of a document, it indicates a part of the document that has been
highlighted due to its likely relevance to the user's current activity.
<p>Do not forget to buy <mark>soft drink</mark> today.</p>
 The <meter> Element
The HTML <meter> tag is used for indicating a scalar measurement within a known
range, or a fractional value.
Also known as a gauge, usage could include displaying disk usage, the amount
raised during fundraising activities, or the relevance of a search query result.
31 | P a g e - L e t s D n D . c o m
32
New Elements in HTML5
It is important to note that the <meter> element is used to represent a range. It is
not appropriate to use this element for representing a single number (such as
how many children someone has) unless there is a known maximum number.
<meter value="2" min="0" max="10">2 out of 10</meter>
<br>
<meter value="0.6">60%</meter>
Note: The <meter> tag should not be used to indicate progress (as in a progress
bar). For progress bars, use the <progress> tag.
 The <progress> Element
When building web sites and web applications, we often need to provide essential
feedback to a user informing them of the progress of their request or task, be it
uploading a file, playing a video, or importing data.
HTML5 makes life easier for us by defining an element whose sole purpose is just
that: the <progress> element.
JavaScript can be used to manipulate the value of progress bar.
The HTML5 specification describes it best:
The progress element represents the completion progress of a task.
Downloading now. Progress...
<progress value="250" max="1000">
<span id="downloadProgress">25</span>%
</progress>
32 | P a g e - L e t s D n D . c o m
33
New Elements in HTML5
 The <ruby> Element
The HTML <ruby> tag is used for specifying Ruby annotations, which is used in
East Asian typography.
Ruby (also spelt rubi) characters are small, annotative glosses that can be placed
above or to the right of a Chinese character when writing logographic languages
such as Chinese or Japanese to show the pronunciation. Ruby annotations, are
usually used as a pronunciation guide for relatively obscure characters.
<p lang="zh-CN">
...
<ruby>
汉
字
</ruby>
</p>
<rt>
<rt>
hàn
zì
</rt>
</rt>
This example demonstrates how to write the <ruby> element into your HTML
code. This example is the pinyin for the word "hanzi" ("chinese character") in
simplified chinese, as used in mainland china. This example requires that your
browser can display Chinese characters.
 The <rt> Element
The HTML <rt> Element embraces pronunciation of character presented in a ruby
annotations, which are for showing pronunciation of East Asian characters and
the <rt> element is used inside of <ruby> element.
Ruby annotations are used in East Asian typography.
Ruby (also spelt rubi) characters are small, annotative glosses that can be placed
above or to the right of a Chinese character when writing logographic languages
such as Chinese or Japanese to show the pronunciation. Ruby annotations, are
usually used as a pronunciation guide for relatively obscure characters.
33 | P a g e - L e t s D n D . c o m
34
New Elements in HTML5
<p lang="zh-CN">
...
<ruby>
汉
字
</ruby>
</p>
<rt>
<rt>
hàn
zì
</rt>
</rt>
 The <rp> Element
The HTML <rp> element is used to provide fall-back parenthesis for browsers nonsupporting ruby annotations. Ruby annotations are for showing pronounciation of
East Asian characters, like using Japanese furigana or Taiwainese bopomofo
characters. The <rp> element is used in the case of lack of <ruby> element
support its content has what should be displayed in order to indicate the
presence of a ruby annotation, usually parentheses.
Ruby annotations are used in East Asian typography.
Ruby (also spelt rubi) characters are small, annotative glosses that can be placed
above or to the right of a Chinese character when writing logographic languages
such as Chinese or Japanese to show the pronunciation. Ruby annotations, are
usually used as a pronunciation guide for relatively obscure characters.
<ruby>
漢 <rt><rp>(</rp>ㄏㄢˋ<rp>)</rp></rt>
</ruby>
 The <time> Element
The HTML <time> tag is used for declaring the date and/or time within an HTML
document.
The HTML <time> element represents either a time on a 24-hour clock or a precise
date in the Gregorian calendar (with optional time and timezone information).
34 | P a g e - L e t s D n D . c o m
35
New Elements in HTML5
This element is intended to be used presenting dates and times in a machine
readable format. This can be helpful for user agents to offer any event scheduling
for user's calendar.
<p>
On Saturdays, we open at
<time>
09:00
</time>
.
</p>
<p>
The concert is
<time datetime="2009-02-18">
next Wednesday
</time>
.
</p>
<p>
We finally hit the road at
<time datetime="2009-02-17T05:00-07:00">
5am last Tuesday
</time>
.
</p>
 The <wbr> Element
The Word Break Opportunity (<wbr>) HTML element represents a position within
text where the browser may optionally break a line, though its line-breaking rules
would not otherwise create a break at that location.
On UTF-8 encoded pages, <wbr> behaves like the U+200B ZERO-WIDTH SPACE
code point. In particular, it behaves like a Unicode bidi BN code point, meaning it
has no effect on bidi-ordering: <div dir=rtl>123,<wbr>456</div> displays, when
not broken on two lines, 123,456 and not 456,123.
35 | P a g e - L e t s D n D . c o m
36
New Elements in HTML5
For the same reason, the <wbr> element does not introduce a hyphen at the line
break point. To make a hyphen appear only at the end of a line, use the soft
hyphen character entity (&shy;) instead.
This element was first implemented in Internet Explorer 5.5 and was officially
defined in HTML5.
<p>
And the world record for the longest place name in an
English-speaking
country is...
<br>
<i>Taumata<wbr>whakatangihanga<wbr>koauau<wbr>o<wbr>tamat
ea<wbr>turi<wbr>pukakapiki<wbr>maunga<wbr>horo<wbr>nuku<wbr>pok
ai<wbr>whenua<wbr>kitanatahu</i>
</p>
<p>
This is the name of a hill in New Zealand.
</p>
<p>
Here's what it looks like without using the
<code>
wbr
</code>
tag...
<i>Taumatawhakatangihangakoauauotamateaturipukakapikimaun
gahoronukupokaiwhenuakitana</i>
</p>
36 | P a g e - L e t s D n D . c o m
Drag and Drop
“Drag and Drop… Anything!
Anywhere!”
38
Drag and Drop
Drag and drop is a very common feature. It is when you "grab" an object and drag
it to a different location.
In HTML5, drag and drop is part of the standard, and any element can be
draggable.
The example below is a simple drag and drop example:
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {
width: 350px;
height: 70px;
padding: 10px;
border: 1px solid #aaaaaa;
}
</style>
<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>
<br>
<img id="drag1" src="img_logo.gif" draggable="true"
ondragstart="drag(event)" width="336" height="69">
</body>
</html>
38 | P a g e - L e t s D n D . c o m
39
Drag and Drop
It might seem complicated, but let’s go through all the different parts of a drag
and drop event.
Make an Element Draggable
First of all: To make an element draggable, set the draggable attribute to true:
<img draggable="true">
What to Drag - ondragstart and setData()
Then, specify what should happen when the element is dragged.
In the example above, the ondragstart attribute calls a function, drag(event), that
specifies what data to be dragged.
39 | P a g e - L e t s D n D . c o m
40
Drag and Drop
The dataTransfer.setData() method sets the data type and the value of the dragged
data:
function drag(ev){
ev.dataTransfer.setData("Text",ev.target.id);
}
In this case, the data type is "Text" and the value is the id of the draggable
element ("drag1").
Where to Drop - ondragover
The ondragover event specifies where the dragged data can be dropped.
By default, data/elements cannot be dropped in other elements. To allow a drop,
we must prevent the default handling of the element.
This is done by calling the event.preventDefault() method for the ondragover event.
Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute calls a function, drop(event):
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
Code explained:
 Call preventDefault() to prevent the browser default handling of the data
(default is open as link on drop)
40 | P a g e - L e t s D n D . c o m
41
Drag and 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
Drag and drop events
At every stage of the drag and drop operation a different event is fired so that the
browser knows what JavaScript code to execute; the events are:
 dragStart : fires when the user starts dragging the element.
 dragEnter : fires when the draggable element is first dragged over the target
element.
 dragOver: fires when the mouse is moved over an element when the drag is
occurring.
 dragLeave: fired if the user’s cursor leaves an element when dragging.
 drag: fires every time we move the mouse during the dragging of our
element.
 drop: fired when the actual drop is performed.
 dragEnd: fires when the user releases the mouse while dragging the object.
With all of these event listeners you have a lot of control over how your interface
works and precisely how it performs in different circumstances.
The Data Transfer object
This is where all the drag and drop magic happens; this object holds the data that
was sent by the drag operation.
41 | P a g e - L e t s D n D . c o m
42
Drag and Drop
The data can be set and retrieved in various ways, the most important ones are:
 dataTransfer.effectAllowed=value: this returns the types of action permitted,
possible values are none, copy, copyLink, copyMove, link, linkMove, move,
all and uninitialized.
 dataTransfer.setData(format, data): adds the specified data and its format.
 dataTransfer.clearData( format ): clears all the data for a specific format.
 dataTransfer.setDragImage(element, x, y): sets the image you wish to drag,
the x and y values specify where the mouse cursor should be (0, 0 will place
it top left).
 data = dataTransfer.getData(format) : As the name says it returns the data
available for a specific format.
42 | P a g e - L e t s D n D . c o m
Geo Location
“Where are you Reader?
May I find you…?”
44
Geo Location
HTML5 offers to locate, where does the reader who is reading the website comes
from. But if and only if reader is willing to reveal that information.
The HTML5 Geolocation API is used to get the geographical position of a user.
Since this can compromise user privacy, the position is not available unless the
user approves it. If a website is using this API to locate the user, user will always
get something popped up on his browser like as below.
With the name of the website, it asks permission to reveal that information. But
when the reader is viewing the website through his PC, it doesn’t give any
accurate information. But when it on a mobile device which includes GPS, it gives
out accurate information where the user viewing the website from.
Let’s go through a code snippet how to do this. Through JavaScript we are
accessing HTML5 DOM(Document Object Model) elements.
<script>
var x = document.getElementById("demo");
function getLocation() {
// Check if Geolocation is supported
if (navigator.geolocation) {
//If supported, run the getCurrentPosition() method
navigator.geolocation.getCurrentPosition(showPosition);
} else {
//If not supported, display a message to the user
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//If the getCurrentPosition() method is successful
//it returns a coordinates object to the function specified in the
//parameter ( showPosition )
function showPosition(position) {
//displays the Latitude and Longitude
x.innerHTML = "Latitude: " + position.coords.latitude
+ "__tag_19$1_Longitude: " + position.coords.longitude;
}
</script>
44 | P a g e - L e t s D n D . c o m
45
Geo Location
<p id="demo">
Click the button to get your coordinates:
</p>
<button onclick="getLocation()">Try It</button>
Let’s see what is happening in here. Use the getCurrentPosition() method to get
the user’s position. It is a simple Geolocation example returning the latitude and
longitude of the user’s position. If everything goes okay, you’ll see some output
like the following.
Latitude: 6.887212
Longitude: 79.9063267
The example above is a very basic Geolocation script, with no error handling.
There are several error points that might comes up in the getCurrentPosition()
method.
 Permission denied – The user did not allow Geolocation
 Position unavailable – It is not possible to get the current location
 Timeout – The operation timed out
To handle those error, we can use the second parameter of the
getCurrentPosition() method is used to handle errors. It specifies a function to run
if it fails to get the user’s location.
Change the calling getCurrentPosition() method as follows by adding the 2nd
parameter.
navigator.geolocation.getCurrentPosition(showPosition,showError);
45 | P a g e - L e t s D n D . c o m
46
Geo Location
Then add the function mentions as below.
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;
}
}
Information that gained from this way can be send to the server side for
necessary operations. If you know how to use Google Maps API, this information
can be converted into a display on the Google Maps.
To display first you have to have a division tag to display the map.
<div id="mapholder"></div>
To send to the Google Maps API service you need to create a latitude and
longitude string in the following format.
latitude_longitude_string = <latitude>,<longitude>
var latlon = position.coords.latitude+","+position.coords.longitude;
What we are going to do now is appends an image inside our division tag. The src
attribute value of the image goes as follows.
var img_url =
"http://maps.googleapis.com/maps/api/staticmapcenter="+latlon+"&zoom=14&si
ze=400x300&sensor=false";
46 | P a g e - L e t s D n D . c o m
47
Geo Location
Here we send our latitude_longitude_string as the staticmapcenter parameter to
Google maps service, so our location position is centered in the map. We set the
zoom level as 14 and size of the image as 400×300 with no sensors.
Next thing is create the image and append it to the division.
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
Check whether if your location appears here correctly. But don’t forget to give the
permission when your browser asked.
47 | P a g e - L e t s D n D . c o m
Storages of HTML5
“Where are you Reader?
May I find you…?”
49
Storages of HTML5
Don’t get jumbled with databases such like MySQL or Postgres…etc. We are
talking about local storages. Something like cookies. But something better than
cookies. It is actually a storage in the user’s web browser. With HTML local
storage, web pages can store data locally within the user’s browser. Previously,
this was done with cookies. However, local storage is more secure and faster. The
data is not included with every server request, but used ONLY when asked for. It
is also possible to store large amounts of data, without affecting the website’s
performance. The data is stored in name/value pairs, and a web page can only
access data stored by itself. Unlike cookies, the storage limit is far larger (at least
5MB) and information is never transferred to the server.
HTML local storage provides two objects for storing data on the client.
 window.localStorage – stores data with no expiration date
 code.sessionStorage – stores data for one session (data is lost when the tab
is closed)
When you are using this feature on your web site, better to check whether user’s
browser supports this feature. Here is the code snippet to check that.
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
Now let’s go for each of the above mentioned objects.
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not
be deleted when the browser is closed, and will be available the next day, week,
or year.
49 | P a g e - L e t s D n D . c o m
50
Storages of HTML5
Here is how you can store a key value pair as a local storage object. Put this code
segment inside the true condition of the above if statement. Key is the first
parameter and the value is the second parameter.
localStorage.setItem("lastname", "Vandebona");
Here is the code segment to retrieve the value of a relevant key stored in the local
storage.
localStorage.getItem("lastname");
Also you can write the above two codes like as this.
//Store
localStorage.lastname = "Vandebona";
//Retrieve
localStorage.lastname;
To remove a key value pair from the local storage, use the following code
segment. It used the key to remove the object.
localStorage.removeItem("lastname");
The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores
the data for only one session. The data is deleted when the user closes the
browser window.
sessionStorage.lastname = “Vandebona”;
These same two methods can be done by using cookies. But with the emergence
of HTML5, now we do not need to waste cookies for this simple functionality.
50 | P a g e - L e t s D n D . c o m
Offline Web Browsing
“What? No Internet…?
But I want to see that again.”
52
Offline Web Browsing
With application cache it is easy to make an offline version of a web application,
by creating a cache manifest file, a way to view a web site without internet once it
loaded.
Application Cache
HTML5 introduces application cache with the intention of when a web application
is cached, it can accessible without an internet connection.
Application cache gives an application three advantages:
 Offline browsing – users can use the application when they’re offline
 Speed – cached resources load faster
 Reduced server load – the browser will only download updated/changed
resources from the server
Let’s see how to create this cache manifest file.
<!DOCTYPE HTML>
<html manifest="demo_html.appcache">
This is the most important code segment if you want to reserve a manifest file on
the user’s web browser to support the offline web browsing. To enable
application cache, include the manifest attribute in the document’stag. Just put
this code line there and view the website once with the online, and view it
repeatedly in offline.
Every page with the manifest attribute specified will be cached when the user
visits it. If the manifest attribute is not specified, the page will not be cached
unless the page is specified directly in the manifest file.
The recommended file extension for manifest files is: “.appcache”
52 | P a g e - L e t s D n D . c o m
53
Offline Web Browsing
Manifest File
The manifest file is a simple text file, which tells the browser what to cache (and
what to never cache).
The manifest file has three sections:
CACHE MANIFEST
Files listed under this header will be cached after they are downloaded for
the first time This is the first line of the file and also it is a required line.
CACHE MANIFEST
/stylesheet.css
/image.gif
/script.js
The manifest file above lists three resources: a CSS file, a GIF image, and a
JavaScript file. When the manifest file is loaded, the browser will download
the three files from the root directory of the web site. Then, whenever the
user is not connected to the internet, the resources will still be available.
NETWORK
Files listed under this header require a connection to the server, and will
never be cached. This specifies the files that should not cached in the web
browser. The NETWORK section below specifies that the file “login.asp”
should never be cached, and will not be available offline.
NETWORK:
login.asp
NETWORK:
*
An asterisk can be used to indicate that all other resources/files require an
internet connection.
53 | P a g e - L e t s D n D . c o m
54
Offline Web Browsing
FALLBACK
Files listed under this header specifies fallback pages if a page is
inaccessible 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 first URI is the resource, the second
is the fallback.
FALLBACK:
/html/ /offline.html
This is a complete manifest file
CACHE MANIFEST
# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js
NETWORK:
login.asp
FALLBACK:
/html/ /offline.html
You might have wondered what the line means with a #hashtag is. Lines starting
with “#” are comment lines, but can also serve another purpose. An application’s
cache is only updated when its manifest file changes. If you edit an image or
change a JavaScript function, those changes will not be re-cached. Updating the
date and version in a comment line is one way to make the browser re-cache your
files.
54 | P a g e - L e t s D n D . c o m
55
Offline Web Browsing
So how long would be this cached information stored in the browser? Once an
application is cached, it remains cached until one of the following happens. Also
user can define the size limit of the cache information.
 The user clears the browser’s cache
 The manifest file is modified (see tip below)
 The application cache is programmatically updated
But remember to be careful what you are going to allow for caching. Once a file is
cached, the browser will continue to show the cached version, even if you change
the file on the server. To ensure the browser updates the cache, you need to
change the manifest file.
55 | P a g e - L e t s D n D . c o m
Server Sent Event
“Feed Me… Feed Me…”
57
Server Sent Event
We guess, you all are much fans of social networking site FaceBook. Or you might
be familiar with Twitter application where you update your statuses with your
followers. Or if you are a cricket lover, you might be familiar with Cricinfo where it
live update what’s happening on the match in text mode. All of these web
applications provide live text feed from the server and present it to the user
without making user to refresh the page. We called this feature, Server-Sent
Events. Server-Sent Events allow a web page to get updates from a server. It is a
one way messaging technique.
A server-sent event is when a web page automatically gets updates from a server.
This was also possible before emerge of HTML5, but the web page would have to
ask if any updates were available. With server-sent events, the updates
come automatically. Facebook/Twitter updates, stock price updates, news feeds,
sport results, etc… are few of the most popular usages.
Let’s look at an example.
First thing to do is checking the availability of browser support.
if (typeof (EventSource) !== "undefined") {
// Yes! Server-sent events support!
// Some code.....
} else {
// Sorry! No server-sent events support..
}
Then you need a server side script where it sends messages to the client browser.
We are using PHP for that purpose.
<?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();
?>
57 | P a g e - L e t s D n D . c o m
58
Server Sent Event
Save this file as demo_sse.php
The server-side event stream syntax is simple. Set the “Content-Type” header to
“text/event-stream”. Now you can start sending event streams. We also specify
that the page should not cache. Output the data to send using echo and always
start with “data:” word and flush the output data back to the web page.
Then we are going to create the EventSource object in the true condition part of
the if statement.
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
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, we put the
received data into the element with id=”result”.
58 | P a g e - L e t s D n D . c o m
59
About Author
About Author
Sandeep Likhar is a freelancer, lives in India and completed
his graduation in 2008. In 2010 he started his career in IT.
Now He is owner of Let’s Design n Develop.
His First and foremost area of focus is E-Books creation
and conversion for Amazon, iTunes, Nook, CreateSpace
etc.
Also he has developed wide range of websites using PHP,
HTML, CSS and CMS.
After 4 year of experience in IT field he decided to write his own programming
language ebooks and make tutorials for quick learners.
‘Learn Basic HTML5’ is the first book written by Sandeep Likhar.
Thanks!
59 | P a g e - L e t s D n D . c o m
60
Thank You
Thank You
Thanks for downloading my book!
I certainly hope you enjoyed ‘Learn Basic HTML5’. It’d be very nice to hear from
you…
Please visit us for more ebooks and free tutorials.
Website: www.letsdnd.com
Contact Us
Email: [email protected]
You can connect and be around with us for new updates from our social network.
Don’t forget to like and follow.
60 | P a g e - L e t s D n D . c o m