0% found this document useful (0 votes)
20 views91 pages

HTML5 Features and Browser Support Guide

HTML5 introduces a simplified DOCTYPE declaration and new semantic elements such as <header>, <footer>, <article>, and <section>, along with multimedia elements like <audio> and <video>. It also features new APIs for functionalities like geolocation and local storage, while removing outdated elements from HTML4. Additionally, HTML5 supports modern browsers and provides methods to ensure compatibility with older browsers through tools like HTML5Shiv.

Uploaded by

vishvpatel865
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views91 pages

HTML5 Features and Browser Support Guide

HTML5 introduces a simplified DOCTYPE declaration and new semantic elements such as <header>, <footer>, <article>, and <section>, along with multimedia elements like <audio> and <video>. It also features new APIs for functionalities like geolocation and local storage, while removing outdated elements from HTML4. Additionally, HTML5 supports modern browsers and provides methods to ensure compatibility with older browsers through tools like HTML5Shiv.

Uploaded by

vishvpatel865
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

HTML5 Introduction

❮ PreviousNext ❯

What is New in HTML5?


The DOCTYPE declaration for HTML5 is very simple:

<!DOCTYPE html>

The character encoding (charset) declaration is also very simple:

<meta charset="UTF-8">

HTML5 Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>

<body>
Content of the document......
</body>

</html>
Try it Yourself »
The default character encoding in HTML5 is UTF-8.

New HTML5 Elements


The most interesting new HTML5 elements are:

New semantic elements like <header>, <footer>, <article>, and <section>.

New attributes of form elements like number, date, time, calendar, and range.
New graphic elements: <svg> and <canvas>.

New multimedia elements: <audio> and <video>.

In the next chapter, HTML5 Support, you will learn how to "teach" older browsers to
handle "unknown" (new) HTML elements.

New HTML5 APIs (Application


Programming Interfaces)
The most interesting new APIs in HTML5 are:

 HTML Geolocation
 HTML Drag and Drop
 HTML Local Storage
 HTML Application Cache
 HTML Web Workers
 HTML SSE

Tip: HTML Local storage is a powerful replacement for cookies.

Removed Elements in HTML5


The following HTML4 elements have been removed in HTML5:

Removed Element Use Instead

<acronym> <abbr>

<applet> <object>
<basefont> CSS

<big> CSS

<center> CSS

<dir> <ul>

<font> CSS

<frame>

<frameset>

<noframes>

<strike> CSS, <s>, or <del>

<tt> CSS

In the chapter HTML5 Migration, you will learn how to easily migrate from HTML4 to
HTML5.
HTML History
Since the early days of the World Wide Web, there have been many versions of
HTML:

Year Version

1989 Tim Berners-Lee invented www

1991 Tim Berners-Lee invented HTML

1993 Dave Raggett drafted HTML+

1995 HTML Working Group defined HTML 2.0

1997 W3C Recommendation: HTML 3.2

1999 W3C Recommendation: HTML 4.01

2000 W3C Recommendation: XHTML 1.0

2008 WHATWG HTML5 First Public Draft

2012 WHATWG HTML5 Living Standard


2014 W3C Recommendation: HTML5

2016 W3C Candidate Recommendation: HTML 5.1

2017 W3C Recommendation: HTML5.1 2nd Edition

2017 W3C Recommendation: HTML5.2

From 1991 to 1999, HTML developed from version 1 to version 4.

In year 2000, the World Wide Web Consortium (W3C) recommended XHTML 1.0. The
XHTML syntax was strict, and the developers were forced to write valid and "well-
formed" code.

In 2004, W3C's decided to close down the development of HTML, in favor of XHTML.

In 2004, WHATWG (Web Hypertext Application Technology Working Group) was


formed. The WHATWG wanted to develop HTML, consistent with how the web was
used, while being backward compatible with older versions of HTML.

In 2004 - 2006, the WHATWG gained support by the major browser vendors.

In 2006, W3C announced that they would support WHATWG.

In 2008, the first HTML5 public draft was released.

In 2012, WHATWG and W3C decided on a separation:

WHATWG wanted to develop HTML as a "Living Standard". A living standard is


always updated and improved. New features can be added, but old functionality
cannot be removed.

The WHATWG HTML5 Living Standard was published in 2012, and is continuously
updated.

W3C wanted to develop a definitive HTML5 and XHTML standard.

The W3C HTML5 Recommendation was released 28 October 2014.


The W3C HTML5.1 2nd Edition Recommendation was released 3 October 2017.

The W3C HTML5.2 Recommendation was released 14 December 2017.

HTML5 Browser Support


❮ PreviousNext ❯

You can teach older browsers to handle HTML5 correctly.

HTML5 Browser Support


HTML5 is supported in all modern browsers.

In addition, all browsers, old and new, automatically handle unrecognized elements
as inline elements.

Because of this, you can "teach" older browsers to handle "unknown" HTML
elements.

You can even teach IE6 (Windows XP 2001) how to handle unknown HTML elements.

Define Semantic Elements as Block


Elements
HTML5 defines eight new semantic elements. All these are block-level elements.

To secure correct behavior in older browsers, you can set the CSS display property
for these HTML elements to block:

header, section, footer, aside, nav, main, article, figure {


display: block;
}
Add New Elements to HTML
You can also add new elements to an HTML page with a browser trick.

This example adds a new element called <myHero> to an HTML page, and defines a
style for it:

Example
<!DOCTYPE html>
<html>
<head>
<script>[Link]("myHero")</script>
<style>
myHero {
display: block;
background-color: #dddddd;
padding: 50px;
font-size: 30px;
}
</style>
</head>
<body>

<h1>A Heading</h1>
<myHero>My Hero Element</myHero>

</body>
</html>
Try it Yourself »

The JavaScript statement [Link]("myHero") is needed to create


a new element in IE 9, and earlier.

Problem With Internet Explorer 8


You could use the solution described above for all new HTML5 elements.

However, IE8 (and earlier) does not allow styling of unknown elements!
Thankfully, Sjoerd Visscher created the HTML5Shiv! The HTML5Shiv is a JavaScript
workaround to enable styling of HTML5 elements in versions of Internet Explorer prior
to version 9.

You will require the HTML5Shiv to provide compatibility for IE Browsers older than IE
9.

Syntax For HTML5Shiv


The HTML5Shiv is placed within the <head> tag.

The HTML5Shiv is a javascript file that is referenced in a <script> tag.

You should use the HTML5Shiv when you are using the new HTML5 elements such
as: <article>, <section>, <aside>, <nav>, <footer>.

You can download the latest version of HTML5shiv from github or reference the CDN
version at [Link]

Syntax
<head>
<!--[if lt IE 9]>
<script src="/js/[Link]"></script>
<![endif]-->
</head>

HTML5Shiv Example
If you do not want to download and store the HTML5Shiv on your site, you could
reference the version found on the CDN site.

The HTML5Shiv script must be placed in the <head> element, after any stylesheets:

Example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!--[if lt IE 9]>
<script
src="[Link]
>
<![endif]-->
</head>
<body>

<section>

<h1>Famous Cities</h1>

<article>
<h2>London</h2>
<p>London is the capital city of England. It is the most populous city
in the United Kingdom, with a metropolitan area of over 13 million
inhabitants.</p>
</article>

<article>
<h2>Paris</h2>
<p>Paris is the capital and most populous city of France.</p>
</article>

<article>
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p>
</article>

</section>

</body>
</html>

New Elements in HTML5


Below is a list of the new HTML5 elements, and a description of what they are used
for.

New Semantic/Structural Elements


HTML5 offers new elements for better document structure:

Tag Description

<article> Defines an article in a document

<aside> Defines content aside from the page content

<bdi> Isolates a part of text that might be formatted in a different direction from

<details> Defines additional details that the user can view or hide

<dialog> Defines a dialog box or window

<figcaption> Defines a caption for a <figure> element

<figure> Defines self-contained content

<footer> Defines a footer for a document or section

<header> Defines a header for a document or section

<main> Defines the main content of a document


<mark> Defines marked/highlighted text

<meter> Defines a scalar measurement within a known range (a gauge)

<nav> Defines navigation links

<progress> Represents the progress of a task

<rp> Defines what to show in browsers that do not support ruby annotations

<rt> Defines an explanation/pronunciation of characters (for East Asian typogr

<ruby> Defines a ruby annotation (for East Asian typography)

<section> Defines a section in a document

<summary> Defines a visible heading for a <details> element

<time> Defines a date/time


<wbr> Defines a possible line-break

Read more about HTML5 Semantics.

New Form Elements


Tag Description

<datalist> Specifies a list of pre-defined options for input controls

<output> Defines the result of a calculation

Read all about old and new form elements in HTML Form Elements.

New Input Types


New Input Types New Input Attributes

 color  autocomplete
 date  autofocus
 datetime  form
 datetime-local  formaction
 email  formenctype
 month  formmethod
 number  formnovalidate
 range  formtarget
 search  height and width
 tel  list
 time  min and max
 url  multiple
 week  pattern (regexp)
 placeholder
 required
 step

Learn all about old and new input types in HTML Input Types.

Learn all about input attributes in HTML Input Attributes.

HTML5 - New Attribute Syntax


HTML5 allows four different syntaxes for attributes.

This example demonstrates the different syntaxes used in an <input> tag:

Type Example

Empty <input type="text" value="John" disabled>

Unquoted <input type="text" value=John>

Double-quoted <input type="text" value="John Doe">

Single-quoted <input type="text" value='John Doe'>


In HTML5, all four syntaxes may be used, depending on what is needed for the
attribute.

HTML5 Graphics
Tag Description

<canvas> Draw graphics, on the fly, via scripting (usually JavaScript)

<picture> Defines a container for multiple image resources

<svg> Draw scalable vector graphics

Read more about HTML5 Canvas.

Read more about HTML5 SVG.

New Media Elements


Tag Description

<audio> Defines sound content

<embed> Defines a container for an external (non-HTML) application


<picture> Defines a container for multiple image resources

<source> Defines multiple media resources for media elements (<video> and <aud

<track> Defines text tracks for media elements (<video> and <audio>)

<video> Defines video or movie

HTML5 Semantic Elements

Semantics is the study of the meanings of words and phrases in a language.

Semantic elements = elements with a meaning.


What are Semantic Elements?
A semantic element clearly describes its meaning to both the browser and the
developer.

Examples of non-semantic elements: <div> and <span> - Tells nothing about its
content.

Examples of semantic elements: <form>, <table>, and <article> - Clearly defines


its content.

New Semantic Elements in HTML5


Many web sites contain HTML code like: <div id="nav"> <div class="header"> <div
id="footer">
to indicate navigation, header, and footer.

HTML5 offers new semantic elements to define different parts of a web page:

 <article>
 <aside>
 <details>
 <figcaption>
 <figure>
 <footer>
 <header>
 <main>
 <mark>
 <nav>
 <section>
 <summary>
 <time>
HTML5 <section> Element
The <section> element defines a section in a document.

"A section is a thematic grouping of content, typically with a heading."

A home page could normally be split into sections for introduction, content, and
contact information.

Example
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is....</p>
</section>

HTML5 <article> Element


The <article> element specifies independent, self-contained content.

An article should make sense on its own, and it should be possible to read it
independently from the rest of the web site.

Examples of where an <article> element can be used:


 Forum post
 Blog post
 Newspaper article

Example
<article>
<h1>What Does WWF Do?</h1>
<p>WWF's mission is to stop the degradation of our planet's natural
environment,
and build a future in which humans live in harmony with nature.</p>
</article>

Nesting <article> in <section> or Vice


Versa?
The<article> element specifies independent, self-contained content.

The <section> element defines section in a document.

Can we use the definitions to decide how to nest those elements? No, we cannot!

So, on the Internet, you will find HTML pages with <section> elements
containing <article> elements, and <article> elements
containing <section> elements.

You will also find pages with <section> elements containing <section> elements,
and <article> elements containing <article> elements.

Example for a newspaper: The sport <article> in the sport section, may have a
technical section in each <article>.

HTML5 <header> Element


The <header> element specifies a header for a document or section.

The <header> element should be used as a container for introductory content.

You can have several <header> elements in one document.


The following example defines a header for an article:

Example
<article>
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's natural
environment,
and build a future in which humans live in harmony with nature.</p>
</article>

HTML5 <footer> Element


The <footer> element specifies a footer for a document or section.

A <footer> element should contain information about its containing element.

A footer typically contains the author of the document, copyright information, links to
terms of use, contact information, etc.

You may have several <footer> elements in one document.

Example
<footer>
<p>Posted by: Hege Refsnes</p>
<p>Contact information: <a href="[Link]
someone@[Link]</a>.</p>
</footer>

HTML5 <nav> Element


The <nav> element defines a set of navigation links.

Notice that NOT all links of a document should be inside a <nav> element.
The <nav> element is intended only for major block of navigation links.
Example
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>

HTML5 <aside> Element


The <aside> element defines some content aside from the content it is placed in
(like a sidebar).

The <aside> content should be related to the surrounding content.

Example
<p>My family and I visited The Epcot center this summer.</p>

<aside>
<h4>Epcot Center</h4>
<p>The Epcot Center is a theme park in Disney World, Florida.</p>
</aside>

HTML5 <figure> and <figcaption>


Elements
The purpose of a figure caption is to add a visual explanation to an image.

In HTML5, an image and a caption can be grouped together in a <figure> element:

Example
<figure>
<img src="pic_trulli.jpg" alt="Trulli">
<figcaption>Fig1. - Trulli, Puglia, Italy.</figcaption>
</figure>
The <img> element defines the image, the <figcaption> element defines the
caption.

Why Semantic Elements?


With HTML4, developers used their own id/class names to style elements: header,
top, bottom, footer, menu, navigation, main, container, content, article, sidebar,
topnav, etc.

This made it impossible for search engines to identify the correct web page content.

With the new HTML5 elements (<header> <footer> <nav> <section>


<article>), this will become easier.

According to the W3C, a Semantic Web: "Allows data to be shared and reused across
applications, enterprises, and communities."

Semantic Elements in HTML5


Below is an alphabetical list of the new semantic elements in HTML5.

The links go to our complete HTML5 Reference.

Tag Description

<article> Defines an article

<aside> Defines content aside from the page content

<details> Defines additional details that the user can view or hide
<figcaption> Defines a caption for a <figure> element

<figure> Specifies self-contained content, like illustrations, diagrams, photos

<footer> Defines a footer for a document or section

<header> Specifies a header for a document or section

<main> Specifies the main content of a document

<mark> Defines marked/highlighted text

<nav> Defines navigation links

<section> Defines a section in a document

<summary> Defines a visible heading for a <details> element

<time> Defines a date/time


HTML Forms

HTML Form Example


First name:
John

Last name:
Doe

Submit

The <form> Element


The HTML <form> element defines a form that is used to collect user input:

<form>
.
form elements
.
</form>

An HTML form contains form elements.

Form elements are different types of input elements, like: text fields, checkboxes,
radio buttons, submit buttons, and more.

The <input> Element


The <input> element is the most important form element.

The <input> element is displayed in several ways, depending on the type attribute.

Here are some examples:


Type Description

<input type="text"> Defines a single-line text input field

<input type="radio"> Defines a radio button (for selecting one of many choic

<input type="submit"> Defines a submit button (for submitting the form)

You will learn a lot more about input types later in this tutorial.

Text Fields
<input type="text"> defines a single-line input field for text input.

Example
A form with two text input fields:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>

This is how it will look like in a browser:

First name:
Last name:

Note: The form itself is not visible. Also note that the default width of an input field is
20 characters.

The <label> Element


Notice the use of the <label> element in the example above.

The <label> tag defines a label for many form elements.

The <label> element is useful for screen-reader users, because the screen-reader
will read out load the label when the user is focused on the input element.

The <label> element also help users who have difficulty clicking on very small
regions (such as radio buttons or checkboxes) - because when the user clicks the text
within the <label> element, it toggles the radio button/checkbox.

The for attribute of the <label> tag should be equal to the id attribute of the
<input> element to bind them together.

Radio Buttons
<input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices.

Example
A form with radio buttons:

<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>
This is how the HTML code above will be displayed in a browser:

Male

Female

Other

The Submit Button


<input type="submit"> defines a button for submitting the form data to a form-
handler.

The form-handler is typically a page on the server with a script for processing input
data.

The form-handler is specified in the form's action attribute.

Example
A form with a submit button:

<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

This is how the HTML code above will be displayed in a browser:

First name:

Last name:
Doe

Submit
The Action Attribute
The action attribute defines the action to be performed when the form is submitted.

Usually, the form data is sent to a page on the server when the user clicks on the
submit button.

In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form
data:

<form action="/action_page.php">

If the action attribute is omitted, the action is set to the current page.

The Target Attribute


The target attribute specifies if the submitted result will open in a new browser tab,
a frame, or in the current window.

The default value is "_self" which means the form will be submitted in the current
window.

To make the form result open in a new browser tab, use the value " _blank".

Example
Here, the submitted result will open in a new browser tab:

<form action="/action_page.php" target="_blank">

Other legal values are "_parent", "_top", or a name representing the name of an
iframe.
The Method Attribute
The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data.

Example
Use the GET method when submitting the form:

<form action="/action_page.php" method="get">

or:

Example
Use the POST method when submitting the form:

<form action="/action_page.php" method="post">

When to Use GET?


The default HTTP method when submitting form data is GET.

However, when GET is used, the form data will be visible in the page's address
field:

/action_page.php?firstname=John&lastname=Doe

Notes on GET:

 Appends form-data into the URL in name/value pairs


 The length of a URL is limited (2048 characters)
 Never use GET to send sensitive data! (will be visible in the URL)
 Useful for form submissions where a user wants to bookmark the result
 GET is better for non-secure data, like query strings in Google

When to Use POST?


Always use POST if the form data contains sensitive or personal information. The
POST method does not display the form data in the page address field.

Notes on POST:

 POST has no size limitations, and can be used to send large amounts of data.
 Form submissions with POST cannot be bookmarked

The Name Attribute


Each input field must have a name attribute to be submitted.

If the name attribute is omitted, the data of that input field will not be sent at all.

Example
This example will not submit the value of the "First name" input field:

<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" value="John"><br><br>
<input type="submit" value="Submit">
</form>

Here is the list of all <form> attributes:

Attribute Description

accept-charset Specifies the charset used in the submitted form (default: the page cha
action Specifies an address (url) where to submit the form (default: the submi

autocomplete Specifies if the browser should autocomplete the form (default: on).

enctype Specifies the encoding of the submitted data (default: is url-encoded).

method Specifies the HTTP method used when submitting the form (default: GE

name Specifies a name used to identify the form (for DOM usage: document.f

novalidate Specifies that the browser should not validate the form.

target Specifies the target of the address in the action attribute (default: _self

The <input> Element


One of the most used form element is the <input> element.

The <input> element can be displayed in several ways, depending on


the type attribute.

Example
<input type="text" id="firstname" name="firstname">
The <select> Element
The <select> element defines a drop-down list:

Example
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <option> elements defines an option that can be selected.

By default, the first item in the drop-down list is selected.

To define a pre-selected option, add the selected attribute to the option:

Example
<option value="fiat" selected>Fiat</option>

Visible Values:
Use the size attribute to specify the number of visible values:

Example
<select name="cars" size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

Allow Multiple Selections:


Use the multiple attribute to allow the user to select more than one value:

Example
<select name="cars" size="4" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <textarea> Element


The <textarea> element defines a multi-line input field (a text area):

Example
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>

The rows attribute specifies the visible number of lines in a text area.

The cols attribute specifies the visible width of a text area.

This is how the HTML code above will be displayed in a browser:

You can also define the size of the text area by using CSS:
Example
<textarea name="message" style="width:200px; height:600px;">
The cat was playing in the garden.
</textarea>

The <button> Element


The <button> element defines a clickable button:

Example
<button type="button" onclick="alert('Hello World!')">Click Me!
</button>

The <fieldset> and <legend>


Elements
The <fieldset> element is used to group related data in a form.

The <legend> element defines a caption for the <fieldset> element.

Example
<form action="/action_page.php">
<fieldset>
<legend>Personalia:</legend>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>

The <datalist> Element


The <datalist> element specifies a list of pre-defined options for
an <input> element.

Users will see a drop-down list of the pre-defined options as they input data.

The list attribute of the <input> element, must refer to the id attribute of
the <datalist> element.

Example
<form action="/action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
The <output> Element
The <output> element represents the result of a calculation (like one performed by a
script).

Example
Perform a calculation and show the result in an <output> element:

<form action="/action_page.php"
oninput="[Link]=parseInt([Link])+parseInt([Link])">
0
<input type="range" id="a" name="a" value="50">
100 +
<input type="number" id="b" name="b" value="50">
=
<output name="x" for="a b"></output>
<br><br>
<input type="submit">
</form>

HTML Input Types


Here are the different input types you can use in HTML:

 <input type="button">
 <input type="checkbox">
 <input type="color">
 <input type="date">
 <input type="datetime-local">
 <input type="email">
 <input type="file">
 <input type="hidden">
 <input type="image">
 <input type="month">
 <input type="number">
 <input type="password">
 <input type="radio">
 <input type="range">
 <input type="reset">
 <input type="search">
 <input type="submit">
 <input type="tel">
 <input type="text">
 <input type="time">
 <input type="url">
 <input type="week">

Input Type Text


<input type="text"> defines a single-line text input field:

Example
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

Input Type Password


<input type="password"> defines a password field:

Example
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd">
</form>

This is how the HTML code above will be displayed in a browser:

Username:

Password:

The characters in a password field are masked (shown as asterisks or circles).

Input Type Submit


<input type="submit"> defines a button for submitting form data to a form-
handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form's action attribute:

Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

This is how the HTML code above will be displayed in a browser:

First name:
John

Last name:
Doe

Submit

If you omit the submit button's value attribute, the button will get a default text:
Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit">
</form>

Input Type Reset


<input type="reset"> defines a reset button that will reset all form values to
their default values:

Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
<input type="reset">
</form>

This is how the HTML code above will be displayed in a browser:

First name:
John

Last name:
Doe
Submit Reset

If you change the input values and then click the "Reset" button, the form-data will
be reset to the default values.

Input Type Radio


<input type="radio"> defines a radio button.

Radio buttons let a user select ONLY ONE of a limited number of choices:

Example
<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>

This is how the HTML code above will be displayed in a browser:

Male

Female

Other
Input Type Checkbox
<input type="checkbox"> defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>

This is how the HTML code above will be displayed in a browser:

I have a bike

I have a car

I have a boat
Input Type Button
<input type="button"> defines a button:

Example
<input type="button" onclick="alert('Hello World!')" value="Click Me!">

This is how the HTML code above will be displayed in a browser:

Input Type Color


The <input type="color"> is used for input fields that should contain a color.

Depending on browser support, a color picker can show up in the input field.

Example
<form>
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor">
</form>

Input Type Date


The <input type="date"> is used for input fields that should contain a date.

Depending on browser support, a date picker can show up in the input field.
Example
<form>
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">
</form>

You can also use the min and max attributes to add restrictions to dates:

Example
<form>
<label for="datemax">Enter a date before 1980-01-01:</label>
<input type="date" id="datemax" name="datemax" max="1979-12-
31"><br><br>
<label for="datemin">Enter a date after 2000-01-01:</label>
<input type="date" id="datemin" name="datemin" min="2000-01-02">
</form>

Input Type Datetime-local


The <input type="datetime-local"> specifies a date and time input field, with no
time zone.

Depending on browser support, a date picker can show up in the input field.

Example
<form>
<label for="birthdaytime">Birthday (date and time):</label>
<input type="datetime-local" id="birthdaytime" name="birthdaytime">
</form>
Input Type Email
The <input type="email"> is used for input fields that should contain an e-mail
address.

Depending on browser support, the e-mail address can be automatically validated


when submitted.

Some smartphones recognize the email type, and add ".com" to the keyboard to
match email input.

Example
<form>
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
</form>

Input Type File


The <input type="file"> defines a file-select field and a "Browse" button for file
uploads.

Example
<form>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
</form>

Input Type Month


The <input type="month"> allows the user to select a month and year.

Depending on browser support, a date picker can show up in the input field.

Example
<form>
<label for="bdaymonth">Birthday (month and year):</label>
<input type="month" id="bdaymonth" name="bdaymonth">
</form>

Input Type Number


The <input type="number"> defines a numeric input field.

You can also set restrictions on what numbers are accepted.

The following example displays a numeric input field, where you can enter a value
from 1 to 5:

Example
<form>
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
</form>

Input Restrictions
Here is a list of some common input restrictions:

Attribute Description

checked Specifies that an input field should be pre-selected when the page l
type="checkbox" or type="radio")
disabled Specifies that an input field should be disabled

max Specifies the maximum value for an input field

maxlength Specifies the maximum number of character for an input field

min Specifies the minimum value for an input field

pattern Specifies a regular expression to check the input value against

readonly Specifies that an input field is read only (cannot be changed)

required Specifies that an input field is required (must be filled out)

size Specifies the width (in characters) of an input field

step Specifies the legal number intervals for an input field

value Specifies the default value for an input field


HTML
<input> readonly Attribute
Example
An HTML form with a read-only input field:

<form action="/action_page.php">
<label for="country">Country:</label>
<input type="text" id="country" name="country" value="Norway" readonl
y><br><br>
<input type="submit" value="Submit">
</form>

Definition and Usage


The readonly attribute is a boolean attribute.

When present, it specifies that an input field is read-only.

A read-only input field cannot be modified (however, a user can tab to it, highlight it,
and copy the text from it).

The readonly attribute can be set to keep a user from changing the value until some
other conditions have been met (like selecting a checkbox, etc.). Then, a JavaScript
can remove the readonly value, and make the input field editable.

HTML
<input> required Attribute
Example
An HTML form with a required input field:

<form action="/action_page.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<input type="submit">
</form>

Definition and Usage


The required attribute is a boolean attribute.

When present, it specifies that an input field must be filled out before submitting the
form.

HTML

<input> disabled Attribute


Example
An HTML form with a disabled input field:

<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" disabled><br><br>
<input type="submit" value="Submit">
</form>

Definition and Usage


The disabled attribute is a boolean attribute.

When present, it specifies that the <input> element should be disabled.

A disabled input element is unusable and un-clickable.

HTML Multimedia

Multimedia on the web is sound, music, videos, movies, and animations.

What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear
or see.

Examples: Images, music, sound, videos, records, films, animations, and more.

Web pages often contain multimedia elements of different types and formats.

In this chapter you will learn about the different multimedia formats.

Browser Support
The first web browsers had support for text only, limited to a single font in a single
color.

Later came browsers with support for colors and fonts, and images!

Audio, video, and animation have been handled differently by the major browsers.
Different formats have been supported, and some formats require extra helper
programs (plug-ins) to work.

Hopefully this will become history. HTML5 multimedia promises an easier future for
multimedia.

Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.

The most common way to discover the type of a file, is to look at the file extension.

Multimedia files have formats and different extensions


like: .swf, .wav, .mp3, .mp4, .mpg, .wmv, and .avi.

Common Video Formats


MP4 is the new and upcoming format for internet video.

MP4 is recommended by YouTube.

MP4 is supported by Flash Players.

MP4 is supported by HTML5.

Format File Description

MPEG .mpg MPEG. Developed by the Moving Pictures Expert Group. The first popu
.mpeg the web. Used to be supported by all browsers, but it is not supported

AVI .avi AVI (Audio Video Interleave). Developed by Microsoft. Commonly used
TV hardware. Plays well on Windows computers, but not in web brows

WMV .wmv WMV (Windows Media Video). Developed by Microsoft. Commonly use
and TV hardware. Plays well on Windows computers, but not in web b

QuickTim .mov QuickTime. Developed by Apple. Commonly used in video cameras an


e well on Apple computers, but not in web browsers. (See MP4)

RealVideo .rm RealVideo. Developed by Real Media to allow video streaming with lo
.ram used for online video and Internet TV, but does not play in web brows

Flash .swf Flash. Developed by Macromedia. Often requires an extra component


.flv web browsers.

Ogg .ogg Theora Ogg. Developed by the [Link] Foundation. Supported by HT

WebM .webm WebM. Developed by the web giants, Mozilla, Opera, Adobe, and Goo
HTML5.

MPEG-4 .mp4 MP4. Developed by the Moving Pictures Expert Group. Based on Quick
or MP4 in newer video cameras and TV hardware. Supported by all HTML5 br
by YouTube.
Audio Formats
MP3 is the newest format for compressed recorded music. The term MP3 has become
synonymous with digital music.

If your website is about recorded music, MP3 is the choice.

Format File Description

MIDI .mid MIDI (Musical Instrument Digital Interface). Main format for all electroni
.midi synthesizers and PC sound cards. MIDI files do not contain sound, but d
played by electronics. Plays well on all computers and music hardware,
browsers.

RealAudi .rm RealAudio. Developed by Real Media to allow streaming of audio with lo
o .ram not play in web browsers.

WMA .wma WMA (Windows Media Audio). Developed by Microsoft. Commonly used
well on Windows computers, but not in web browsers.

AAC .aac AAC (Advanced Audio Coding). Developed by Apple as the default form
on Apple computers, but not in web browsers.

WAV .wav WAV. Developed by IBM and Microsoft. Plays well on Windows, Macinto
systems. Supported by HTML5.
Ogg .ogg Ogg. Developed by the [Link] Foundation. Supported by HTML5.

MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3 is the most pop
players. Combines good compression (small files) with high quality. Sup
browsers.

MP4 .mp4 MP4 is a video format, but can also be used for audio. MP4 video is the
on the internet. This leads to automatic support for MP4 audio by all bro

Video:

Playing Videos in HTML


Before HTML5, a video could only be played in a browser with a plug-in (like flash).

The HTML5 <video> element specifies a standard way to embed a video in a web
page.

Browser Support
The numbers in the table specify the first browser version that fully supports
the <video> element.

Element

<video> 4.0 9.0 3.5 4.0


The HTML <video> Element
To show a video in HTML, use the <video> element:

Example
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="[Link]" type="video/ogg">
Your browser does not support the video tag.
</video>

How it Works
The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width
are not set, the page might flicker while the video loads.

The <source> element allows you to specify alternative video files which the browser
may choose from. The browser will use the first recognized format.

The text between the <video> and </video> tags will only be displayed in browsers
that do not support the <video> element.

HTML <video> Autoplay


To start a video automatically use the autoplay attribute:
Example
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="[Link]" type="video/ogg">
Your browser does not support the video tag.
</video>

HTML Video - Browser Support


In HTML5, there are 3 supported video formats: MP4, WebM, and Ogg.

The browser support for the different formats is:

Browser MP4 WebM Ogg

Internet Explorer YES NO NO

Chrome YES YES YES

Firefox YES YES YES

Safari YES NO NO

Opera YES (from Opera 25) YES YES


HTML Video - Media Types
File Format Media Type

MP4 video/mp4

WebM video/webm

Ogg video/ogg

HTML Video - Methods, Properties, and


Events
HTML5 defines DOM methods, properties, and events for the <video> element.

This allows you to load, play, and pause videos, as well as setting duration and
volume.

There are also DOM events that can notify you when a video begins to play, is
paused, etc.

HTML5 Video Tags


Tag Description
<video> Defines a video or movie

<source> Defines multiple media resources for media elements, such as <vid

<track> Defines text tracks in media players

HTML5 Audio

Audio on the Web


Before HTML5, audio files could only be played in a browser with a plug-in (like flash).

The HTML5 <audio> element specifies a standard way to embed audio in a web
page.

Browser Support
The numbers in the table specify the first browser version that fully supports
the <audio> element.

Element

<audio> 4.0 9.0 3.5 4.0


The HTML <audio> Element
To play an audio file in HTML, use the <audio> element:

Example
<audio controls>
<source src="[Link]" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

HTML Audio - How It Works


The controls attribute adds audio controls, like play, pause, and volume.

The <source> element allows you to specify alternative audio files which the browser
may choose from. The browser will use the first recognized format.

The text between the <audio> and </audio> tags will only be displayed in browsers
that do not support the <audio> element.

HTML Audio - Browser Support


In HTML5, there are 3 supported audio formats: MP3, WAV, and OGG.

The browser support for the different formats is:

Browser MP3 WAV OGG

Edge/IE YES NO NO
Chrome YES YES YES

Firefox YES YES YES

Safari YES YES NO

Opera YES YES YES

HTML Audio - Media Types


File Format Media Type

MP3 audio/mpeg

OGG audio/ogg

WAV audio/wav

HTML Audio - Methods, Properties, and


Events
HTML5 defines DOM methods, properties, and events for the <audio> element.

This allows you to load, play, and pause audios, as well as set duration and volume.

There are also DOM events that can notify you when an audio begins to play, is
paused, etc.

For a full DOM reference, go to our HTML5 Audio/Video DOM Reference.

HTML5 Audio Tags


Tag Description

<audio> Defines sound content

<source> Defines multiple media resources for media elements, such as <video>

HTML Plug-ins
The purpose of a plug-in is to extend the functionality of a web browser.

HTML Helpers (Plug-ins)


Helper applications (plug-ins) are computer programs that extend the standard
functionality of a web browser.

Examples of well-known plug-ins are Java applets.

Plug-ins can be added to web pages with the <object> tag or the <embed> tag.
Plug-ins can be used for many purposes: display maps, scan for viruses, verify your
bank id, etc.

The <object> Element


The <object> element is supported by all browsers.

The <object> element defines an embedded object within an HTML document.

It is used to embed plug-ins (like Java applets, PDF readers, Flash Players) in web
pages.

Example
<object width="400" height="50" data="[Link]"></object>

The <object> element can also be used to include HTML in HTML:

Example
<object width="100%" height="500px" data="[Link]"></object>

Or images if you like:

Example
<object data="[Link]"></object>

The <embed> Element


The <embed> element is supported in all major browsers.

The <embed> element also defines an embedded object within an HTML document.

Web browsers have supported the <embed> element for a long time. However, it
has not been a part of the HTML specification before HTML5.
Example
<embed width="400" height="50" src="[Link]">

The <embed> element can also be used to include HTML in HTML:

Example
<embed width="100%" height="500px" src="[Link]">

Or images if you like:

Example
<embed src="[Link]">

HTML YouTube Videos


The easiest way to play videos in HTML, is to use YouTube.

Struggling with Video Formats?


Earlier in this tutorial, you have seen that you might have to convert your videos to
different formats to make them play in all browsers.

Converting videos to different formats can be difficult and time-consuming.

An easier solution is to let YouTube play the videos in your web page.

YouTube Video Id
YouTube will display an id (like tgbNymZ7vqY), when you save (or play) a video.

You can use this id, and refer to your video in the HTML code.
Playing a YouTube Video in HTML
To play your video on a web page, do the following:

 Upload the video to YouTube


 Take a note of the video id
 Define an <iframe> element in your web page
 Let the src attribute point to the video URL
 Use the width and height attributes to specify the dimension of the player
 Add any other parameters to the URL (see below)

Example - Using iFrame (recommended)


<iframe width="420" height="315"
src="[Link]
</iframe>

YouTube Autoplay
You can have your video start playing automatically when a user visits that page by
adding a simple parameter to your YouTube URL.

Note: Take careful consideration when deciding to autoplay your videos.


Automatically starting a video can annoy your visitor and end up causing more harm
than good.

Value 0 (default): The video will not play automatically when the player loads.

Value 1: The video will play automatically when the player loads.

YouTube - Autoplay
<iframe width="420" height="315"
src="[Link]
</iframe>

YouTube Playlist
A comma separated list of videos to play (in addition to the original URL).
YouTube Loop
Value 0 (default): The video will play only once.

Value 1: The video will loop (forever).

YouTube - Loop
<iframe width="420" height="315"
src="[Link]
playlist=tgbNymZ7vqY&loop=1">
</iframe>

YouTube Controls
Value 0: Player controls does not display.

Value 1 (default): Player controls display.

YouTube - Controls
<iframe width="420" height="315"
src="[Link]
</iframe>

YouTube - Using <object> or


<embed>
Note: YouTube <object> and <embed> were deprecated from January 2015. You
should migrate your videos to use <iframe> instead.

Example - Using <object> (deprecated)


<object width="420" height="315"
data="[Link]
</object>

Example - Using <embed> (deprecated)


<embed width="420" height="315"
src="[Link]
HTML5 Canvas

The HTML <canvas> element is used to draw graphics on a web page.

The graphic to the left is created with <canvas>. It shows four elements: a red
rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.

What is HTML Canvas?


The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.

The <canvas> element is only a container for graphics. You must use JavaScript to
actually draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding
images.

Browser Support
The numbers in the table specify the first browser version that fully supports
the <canvas> element.

Element

<canvas> 4.0 9.0 2.0 3.1


HTML Canvas Drawing

Draw on the Canvas With JavaScript


All drawing on the HTML canvas must be done with JavaScript:

Example
<script>
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link] = "#FF0000";
[Link](0, 0, 150, 75);
</script>

Step 1: Find the Canvas Element


First of all, you must find the <canvas> element.

This is done by using the HTML DOM method getElementById():

var canvas = [Link]("myCanvas");

Step 2: Create a Drawing Object


Secondly, you need a drawing object for the canvas.

The getContext() is a built-in HTML object, with properties and methods for drawing:

var ctx = [Link]("2d");


Step 3: Draw on the Canvas
Finally, you can draw on the canvas.

Set the fill style of the drawing object to the color red:

[Link] = "#FF0000";

The fillStyle property can be a CSS color, a gradient, or a pattern. The default fillStyle
is black.

The fillRect(x,y,width,height) method draws a rectangle, filled with the fill style, on
the canvas:

[Link](0, 0, 150, 75);

Canvas Coordinates
The HTML canvas is a two-dimensional grid.

The upper-left corner of the canvas has the coordinates (0,0)

In the previous chapter, you saw this method used: fillRect(0,0,150,75).

This means: Start at the upper-left corner (0,0) and draw a 150x75 pixels rectangle.

Coordinates Example
Mouse over the rectangle below to see its x and y coordinates:

Draw a Line
To draw a straight line on a canvas, use the following methods:

 moveTo(x,y) - defines the starting point of the line


 lineTo(x,y) - defines the ending point of the line

To actually draw the line, you must use one of the "ink" methods, like stroke().

Example
Define a starting point in position (0,0), and an ending point in position (200,100).
Then use the stroke() method to actually draw the line:

var canvas = [Link]("myCanvas");


var ctx = [Link]("2d");
[Link](0, 0);
[Link](200, 100);
[Link]();

Try it Yourself »

ADVERTISEMENT

Draw a Circle
To draw a circle on a canvas, use the following methods:

 beginPath() - begins a path


 arc(x,y,r,startangle,endangle) - creates an arc/curve. To create a circle with
arc(): Set start angle to 0 and end angle to 2*[Link]. The x and y parameters
define the x- and y-coordinates of the center of the circle. The r parameter
defines the radius of the circle.

Example
Define a circle with the arc() method. Then use the stroke() method to actually draw
the circle:

var canvas = [Link]("myCanvas");


var ctx = [Link]("2d");
[Link]();
[Link](95, 50, 40, 0, 2 * [Link]);
[Link]();
Canvas - Gradients
Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas
are not limited to solid colors.

There are two different types of gradients:

 createLinearGradient(x,y,x1,y1) - creates a linear gradient


 createRadialGradient(x,y,r,x1,y1,r1) - creates a radial/circular gradient

Once we have a gradient object, we must add two or more color stops.

The addColorStop() method specifies the color stops, and its position along the
gradient. Gradient positions can be anywhere between 0 to 1.

To use the gradient, set the fillStyle or strokeStyle property to the gradient, then
draw the shape (rectangle, text, or a line).

Using createLinearGradient()
Example
Create a linear gradient. Fill rectangle with the gradient:

JavaScript:

var c = [Link]("myCanvas");
var ctx = [Link]("2d");

// Create gradient
var grd = [Link](0, 0, 200, 0);
[Link](0, "red");
[Link](1, "white");

// Fill with gradient


[Link] = grd;
[Link](10, 10, 150, 80);

Try it Yourself »

ADVERTISEMENT
Using createRadialGradient():
Example
Create a radial/circular gradient. Fill rectangle with the gradient:

JavaScript:

var c = [Link]("myCanvas");
var ctx = [Link]("2d");

// Create gradient
var grd = [Link](75, 50, 5, 90, 60, 100);
[Link](0, "red");
[Link](1, "white");

// Fill with gradient


[Link] = grd;
[Link](10, 10, 150, 80);

Drawing Text on the Canvas


To draw text on a canvas, the most important property and methods are:

 font - defines the font properties for the text


 fillText(text,x,y) - draws "filled" text on the canvas
 strokeText(text,x,y) - draws text on the canvas (no fill)

Using fillText()
Example
Set font to 30px "Arial" and write a filled text on the canvas:

JavaScript:

var canvas = [Link]("myCanvas");


var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("Hello World", 10, 50);

Try it Yourself »

Using strokeText()
Example
Set font to 30px "Arial" and write a text, with no fill, on the canvas:

JavaScript:

var canvas = [Link]("myCanvas");


var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("Hello World", 10, 50);

Try it Yourself »

ADVERTISEMENT

Add Color and Center Text


Example
Set font to 30px "Comic Sans MS" and write a filled red text in the center of the
canvas:

JavaScript:

var canvas = [Link]("myCanvas");


var ctx = [Link]("2d");
[Link] = "30px Comic Sans MS";
[Link] = "red";
[Link] = "center";
[Link]("Hello World", [Link]/2, [Link]/2);
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border
and no content.

The markup looks like this:

<canvas id="myCanvas" width="200" height="100"></canvas>

Note: Always specify an id attribute (to be referred to in a script), and


a width and height attribute to define the size of the canvas. To add a border, use
the style attribute.

Here is an example of a basic, empty canvas:

Example
<canvas id="myCanvas" width="200" height="100" style="border:1px solid
#000000;">
</canvas>

Draw a Line
Example
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link](0, 0);
[Link](200, 100);
[Link]();

Draw a Circle
Example
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link]();
[Link](95, 50, 40, 0, 2 * [Link]);
[Link]();
Draw a Text
Example
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("Hello World", 10, 50);

Stroke Text
Example
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("Hello World", 10, 50);

Draw Linear Gradient


Example
var c = [Link]("myCanvas");
var ctx = [Link]("2d");

// Create gradient
var grd = [Link](0, 0, 200, 0);
[Link](0, "red");
[Link](1, "white");

// Fill with gradient


[Link] = grd;
[Link](10, 10, 150, 80);

Draw Circular Gradient


Example
var c = [Link]("myCanvas");
var ctx = [Link]("2d");

// Create gradient
var grd = [Link](75, 50, 5, 90, 60, 100);
[Link](0, "red");
[Link](1, "white");
// Fill with gradient
[Link] = grd;
[Link](10, 10, 150, 80);

Draw Image
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
var img = [Link]("scream");
[Link](img, 10, 10);

HTML5 SVG

What is SVG?
 SVG stands for Scalable Vector Graphics
 SVG is used to define graphics for the Web
 SVG is a W3C recommendation

The HTML <svg> Element


The HTML <svg> element is a container for SVG graphics.

SVG has several methods for drawing paths, boxes, circles, text, and graphic images.

Browser Support
The numbers in the table specify the first browser version that fully supports
the <svg> element.
Element

<svg> 4.0 9.0 3.0 3.2

SVG Circle
Example
<!DOCTYPE html>
<html>
<body>

<svg width="100" height="100">


<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fil
l="yellow" />
</svg>

</body>
</html>

SVG Rectangle

Example
<svg width="400" height="100">
<rect width="400" height="100" style="fill:rgb(0,0,255);stroke-
width:10;stroke:rgb(0,0,0)" />
</svg>

SVG Rounded Rectangle


Example
<svg width="400" height="180">
<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</svg>

SVG Star
Example
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>

SVG Logo
SVG

Example
<svg height="130" width="500">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-
opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-
opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="50"
y="86">SVG</text>
Sorry, your browser does not support inline SVG.
</svg>

Differences Between SVG and Canvas


SVG is a language for describing 2D graphics in XML.

Canvas draws 2D graphics, on the fly (with a JavaScript).

SVG is XML based, which means that every element is available within the SVG DOM.
You can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG object


are changed, the browser can automatically re-render the shape.
Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten
by the browser. If its position should be changed, the entire scene needs to be
redrawn, including any objects that might have been covered by the graphic.

Comparison of Canvas and SVG


The table below shows some important differences between Canvas and SVG:

Canvas SVG

 Resolution dependent  Resolution independent


 No support for event handlers  Support for event handlers
 Poor text rendering capabilities  Best suited for applications with lar
 You can save the resulting image (Google Maps)
as .png or .jpg  Slow rendering if complex (anything
 Well suited for graphic-intensive games lot will be slow)
 Not suited for game applications

HTML5 Geolocation
The HTML Geolocation API is used to locate a user's position.

Try It

Locate the User's Position


The HTML Geolocation API is used to get the geographical position of a user.

Since this can compromise privacy, the position is not available unless the user approves it.

Note: Geolocation is most accurate for devices with GPS, like smartphone.
Browser Support
The numbers in the table specify the first browser version that fully supports Geolocation.

API

Geolocation 5.0 - 49.0 (http) 9.0 3.5 5.0


50.0 (https)

Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as
HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the
users location will no longer function.

Using HTML Geolocation


The getCurrentPosition() method is used to return the user's position.

The example below returns the latitude and longitude of the user's position:

Example
<script>
var x = [Link]("demo");
function getLocation() {
if ([Link]) {
[Link](showPosition);
} else {
[Link] = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
[Link] = "Latitude: " + [Link] +
"<br>Longitude: " + [Link];
}
</script>

Example explained:

 Check if Geolocation is supported


 If supported, run the getCurrentPosition() method. If not, display a message to the
user
 If the getCurrentPosition() method is successful, it returns a coordinates object to the
function specified in the parameter (showPosition)
 The showPosition() function outputs the Latitude and Longitude

The example above is a very basic Geolocation script, with no error handling.

Handling Errors and Rejections


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:

Example
function showError(error) {
switch([Link]) {
case error.PERMISSION_DENIED:
[Link] = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
[Link] = "Location information is unavailable."
break;
case [Link]:
[Link] = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
[Link] = "An unknown error occurred."
break;
}
}

Displaying the Result in a Map


To display the result in a map, you need access to a map service, like Google Maps.

In the example below, the returned latitude and longitude is used to show the location in a
Google Map (using a static image):

Example
function showPosition(position) {
var latlon = [Link] + "," + [Link];

var img_url = "[Link]


"+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";

[Link]("mapholder").innerHTML = "<img src='"+img_url+"'>";


}

Location-specific Information
This page has demonstrated how to show a user's position on a map.

Geolocation is also very useful for location-specific information, like:

 Up-to-date local information


 Showing Points-of-interest near the user
 Turn-by-turn navigation (GPS)

The getCurrentPosition() Method - Return


Data
The getCurrentPosition() method returns an object on success. The latitude, longitude and
accuracy properties are always returned. The other properties are returned if available:

Property Returns

[Link] The latitude as a decimal number (always returned)

[Link] The longitude as a decimal number (always returned)

[Link] The accuracy of position (always returned)


[Link] The altitude in meters above the mean sea level (returned if available)

[Link] The altitude accuracy of position (returned if available)


y

[Link] The heading as degrees clockwise from North (returned if available)

[Link] The speed in meters per second (returned if available)

timestamp The date/time of the response (returned if available)

Geolocation Object - Other interesting


Methods
The Geolocation object also has other interesting methods:

 watchPosition() - Returns the current position of the user and continues to return
updated position as the user moves (like the GPS in a car).
 clearWatch() - Stops the watchPosition() method.

The example below shows the watchPosition() method. You need an accurate GPS device to
test this (like smartphone):

Example
<script>
var x = [Link]("demo");
function getLocation() {
if ([Link]) {
[Link](showPosition);
} else {
[Link] = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
[Link] = "Latitude: " + [Link] +
"<br>Longitude: " + [Link];
}
</script>

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: Any element can be draggable.

Browser Support
The numbers in the table specify the first browser version that fully supports Drag
and Drop.

API

Drag and Drop 4.0 9.0 3.5 6.0

HTML Drag and Drop Example


The example below is a simple drag and drop example:

Example
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
[Link]();
}

function drag(ev) {
[Link]("text", [Link]);
}

function drop(ev) {
[Link]();
var data = [Link]("text");
[Link]([Link](data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></


div>

<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(e


vent)" width="336" height="69">

</body>
</html>

It might seem complicated, but lets 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.

The [Link]() method sets the data type and the value of the
dragged data:

function drag(ev) {
[Link]("text", [Link]);
}

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 [Link]() method for the ondragover


event:

[Link]()

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) {
[Link]();
var data = [Link]("text");
[Link]([Link](data));
}

Code explained:

 Call preventDefault() to prevent the browser default handling of the data


(default is open as link on drop)
 Get the dragged data with the [Link]() 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

HTML5 Web Storage

HTML web storage; better than cookies.

What is HTML Web Storage?


With web storage, web applications can store data locally within the user's browser.

Before HTML5, application data had to be stored in cookies, included in every server
request. Web storage is more secure, and large amounts of data can be stored
locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never
transferred to the server.

Web storage is per origin (per domain and protocol). All pages, from one origin, can
store and access the same data.

Browser Support
The numbers in the table specify the first browser version that fully supports Web
Storage.
API

Web Storage 4.0 8.0 3.5 4.0

HTML Web Storage Objects


HTML web storage provides two objects for storing data on the client:

 [Link] - stores data with no expiration date


 [Link] - stores data for one session (data is lost when the
browser tab is closed)

Before using web storage, check browser support for localStorage and
sessionStorage:

if (typeof(Storage) !== "undefined") {


// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}

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.

Example
// Store
[Link]("lastname", "Smith");

// Retrieve
[Link]("result").innerHTML =
[Link]("lastname");
Example explained:

 Create a localStorage name/value pair with name="lastname" and


value="Smith"
 Retrieve the value of "lastname" and insert it into the element with id="result"

The example above could also be written like this:

// Store
[Link] = "Smith";
// Retrieve
[Link]("result").innerHTML = [Link];

The syntax for removing the "lastname" localStorage item is as follows:

[Link]("lastname");

Note: Name/value pairs are always stored as strings. Remember to convert them to
another format when needed!

The following example counts the number of times a user has clicked a button. In this
code the value string is converted to a number to be able to increase the counter:

Example
if ([Link]) {
[Link] = Number([Link]) + 1;
} else {
[Link] = 1;
}
[Link]("result").innerHTML = "You have clicked the
button " +
[Link] + " time(s).";

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 specific
browser tab.

The following example counts the number of times a user has clicked a button, in the
current session:
Example
if ([Link]) {
[Link] = Number([Link]) + 1;
} else {
[Link] = 1;
}
[Link]("result").innerHTML = "You have clicked the
button " +
[Link] + " time(s) in this session.";

HTML5 Web Workers

A web worker is a JavaScript running in the background, without affecting the


performance of the page.

What is a Web Worker?


When executing scripts in an HTML page, the page becomes unresponsive until the script is
finished.

A web worker is a JavaScript that runs in the background, independently of other scripts,
without affecting the performance of the page. You can continue to do whatever you want:
clicking, selecting things, etc., while the web worker runs in the background.

Browser Support
The numbers in the table specify the first browser version that fully support Web Workers.
API

Web Workers 4.0 10.0 3.5 4.0

HTML Web Workers Example


The example below creates a simple web worker that count numbers in the background:

Example
Count numbers:

Start Worker Stop Worker

Check Web Worker Support


Before creating a web worker, check whether the user's browser supports it:

if (typeof(Worker) !== "undefined") {


// Yes! Web worker support!
// Some code.....
} else {
// Sorry! No Web Worker support..
}

Create a Web Worker File


Now, let's create our web worker in an external JavaScript.

Here, we create a script that counts. The script is stored in the "demo_workers.js" file:

var i = 0;

function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}

timedCount();

The important part of the code above is the postMessage() method - which is used to post a
message back to the HTML page.

Note: Normally web workers are not used for such simple scripts, but for more CPU intensive
tasks.

Create a Web Worker Object


Now that we have the web worker file, we need to call it from an HTML page.

The following lines checks if the worker already exists, if not - it creates a new web worker
object and runs the code in "demo_workers.js":

if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}

Then we can send and receive messages from the web worker.

Add an "onmessage" event listener to the web worker.

[Link] = function(event){
[Link]("result").innerHTML = [Link];
};

When the web worker posts a message, the code within the event listener is executed. The
data from the web worker is stored in [Link].

Terminate a Web Worker


When a web worker object is created, it will continue to listen for messages (even after the
external script is finished) until it is terminated.

To terminate a web worker, and free browser/computer resources, use


the terminate() method:

[Link]();
Reuse the Web Worker
If you set the worker variable to undefined, after it has been terminated, you can reuse the
code:

w = undefined;

Full Web Worker Example Code


We have already seen the Worker code in the .js file. Below is the code for the HTML page:

Example
<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>


<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>

<script>
var w;

function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
[Link] = function(event) {
[Link]("result").innerHTML = [Link];
};
} else {
[Link]("result").innerHTML = "Sorry! No Web Worker
support.";
}
}

function stopWorker() {
[Link]();
w = undefined;
}
</script>
</body>
</html>

You might also like