Introduction

- What is HTML?

HTML is the standard markup language for creating Web pages.

  • HTML stands for Hyper Text Markup Language
  • HTML describes the structure of a Web page
  • HTML consists of a series of elements
  • HTML elements tell the browser how to display the content
  • HTML elements are represented by tags
  • HTML tags label pieces of content such as "heading", "paragraph", "table", and so on
  • Browsers do not display the HTML tags, but use them to render the content of the page

- A Simple HTML Document

<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
		<h1>My First Heading</h1>
		<p>My first paragraph.</p>
	</body>
</html>

- Tags

HTML tags are element names surrounded by angle brackets:

<tagname>content goes here...</tagname>
  • HTML tags normally come in pairs like <p> and </p>
  • The first tag in a pair is the start tag, the second tag is the end tag
  • The end tag is written like the start tag, but with a forward slash inserted before the tag name

- Web Browsers

The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents and display them. The browser does not display the HTML tags, but uses them to determine how to display the document.

- The <!DOCTYPE> Declaration

The <!DOCTYPE> declaration represents the document type, and helps browsers to display web pages correctly. It must only appear once, at the top of the page (before any HTML tags). The <!DOCTYPE> declaration is not case sensitive. The <!DOCTYPE> declaration for HTML5 is:

<!DOCTYPE html>

- Versions

Since the early days of the web, there have been many versions of HTML:

  • HTML - 1991
  • HTML 2.0 - 1995
  • HTML 3.2 - 1997
  • HTML 4.01 - 1999
  • XHTML - 2000
  • HTML5 - 2014

Basic

- Documents

All HTML documents must start with a document type declaration: <!DOCTYPE html>. The HTML document itself begins with <html> and ends with </html>. The visible part of the HTML document is between <body> and </body>.

- Headings

HTML headings are defined with the <h1> to <h6> tags. <h1> defines the most important heading. <h6> defines the least important heading:

<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>

- Paragraphs

HTML paragraphs are defined with the <p> tag:

<p>This is a paragraph.</p>

The HTML <pre> element defines preformatted text.

The text inside a <pre> element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks:

<pre>
	My Bonnie lies over the ocean.
	My Bonnie lies over the sea.
	My Bonnie lies over the ocean.
	Oh, bring back my Bonnie to me.
</pre>

- Links

HTML links are defined with the <a> tag:

<a href="https://alishoff.com/">This is a link</a>

The link's destination is specified in the href attribute.  Attributes are used to provide additional information about HTML elements.

- Images

HTML images are defined with the <img> tag. The source file (src), alternative text (alt), width, and height are provided as attributes:

<img src="https://alishoff.com/uploads/5dc0fc8dca83a.png" alt="HTML" width="100" height="150">

- Buttons

HTML buttons are defined with the <button> tag:

<button>Click me</button>

- Lists

HTML lists are defined with the <ul> (unordered/bullet list) or the <ol> (ordered/numbered list) tag, followed by <li> tags (list items):

<ul>
	<li>Coffee</li>
	<li>Tea</li>
	<li>Milk</li>
</ul>

<ol>
	<li>Coffee</li>
	<li>Tea</li>
	<li>Milk</li>
</ol>

Attributes

Attributes provide additional information about HTML elements.

  • alt - Specifies an alternative text for an image, when the image cannot be displayed
  • disabled - Specifies that an input element should be disabled
  • href - Specifies the URL (web address) for a link
  • id - Specifies a unique id for an element
  • src - Specifies the URL (web address) for an image
  • style - Specifies an inline CSS style for an element
  • title - Specifies extra information about an element (displayed as a tool tip)

Styles

  • Use the style attribute for styling HTML elements
  • Use background-color for background color
  • Use color for text colors
  • Use font-family for text fonts
  • Use font-size for text sizes
  • Use text-align for text alignment

Formatting

Formatting elements were designed to display special types of text:

  • <b> - Bold text
  • <strong> - Important text
  • <i> - Italic text
  • <em> - Emphasized text
  • <mark> - Marked text
  • <small> - Small text
  • <del> - Deleted text
  • <ins> - Inserted text
  • <sub> - Subscript text
  • <sup> - Superscript text

Quotation and citation

  • <abbr> - Defines an abbreviation or acronym
  • <address> - Defines contact information for the author/owner of a document
  • <bdo> - Defines the text direction
  • <blockquote> - Defines a section that is quoted from another source
  • <cite> - Defines the title of a work
  • <q> - Defines a short inline quotation

Colors

HTML colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.

- Color names

  • Tomato
  • Orange
  • DodgerBlue
  • MediumSeaGreen
  • Gray etc.

- RGB

In HTML, a color can be specified as an RGB value, using this formula:

rgb(red, green, blue)

Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.

For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others are set to 0.

- HEX

In HTML, a color can be specified using a hexadecimal value in the form:

#rrggbb

Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as decimal 0-255).

For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and the others are set to the lowest value (00).

- HSL

In HTML, a color can be specified using hue, saturation, and lightness (HSL) in the form:

hsl(hue, saturation, lightness)

Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.

Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.

Lightness is also a percentage, 0% is black, 50% is neither light or dark, 100% is white.

- RGBA

RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color.

An RGBA color value is specified with:

rgba(red, green, blue, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all).

- HSLA

HSLA color values are an extension of HSL color values with an alpha channel - which specifies the opacity for a color.

An HSLA color value is specified with:

hsla(hue, saturation, lightness, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all).


CSS

CSS stands for Cascading Style Sheets.

CSS describes how HTML elements are to be displayed on screen, paper, or in other media.

  • Use the HTML style attribute for inline styling
  • Use the HTML <style> element to define internal CSS
  • Use the HTML <link> element to refer to an external CSS file
  • Use the HTML <head> element to store <style> and <link> elements
  • Use the CSS color property for text colors
  • Use the CSS font-family property for text fonts
  • Use the CSS font-size property for text sizes
  • Use the CSS border property for borders
  • Use the CSS padding property for space inside the border
  • Use the CSS margin property for space outside the border

Links

Links are found in nearly all web pages. Links allow users to click their way from page to page.

- The target Attribute

The target attribute specifies where to open the linked document.

The target attribute can have one of the following values:

  • _blank - Opens the linked document in a new window or tab
  • _self - Opens the linked document in the same window/tab as it was clicked (this is default)
  • _parent - Opens the linked document in the parent frame
  • _top - Opens the linked document in the full body of the window
  • framename - Opens the linked document in a named frame

Summary

  • Use the <a> element to define a link
  • Use the href attribute to define the link address
  • Use the target attribute to define where to open the linked document
  • Use the <img> element (inside <a>) to use an image as a link
  • Use the id attribute (id="value") to define bookmarks in a page
  • Use the href attribute (href="#value") to link to the bookmark

Images

  • Use the HTML <img> element to define an image
  • Use the HTML src attribute to define the URL of the image
  • Use the HTML alt attribute to define an alternate text for an image, if it cannot be displayed
  • Use the HTML width and height attributes to define the size of the image
  • Use the CSS width and height properties to define the size of the image (alternatively)
  • Use the CSS float property to let the image float
  • Use the HTML <map> element to define an image-map
  • Use the HTML <area> element to define the clickable areas in the image-map
  • Use the HTML <img>'s element usemap attribute to point to an image-map
  • Use the HTML <picture> element to show different images for different devices

Image maps

The <map> tag defines an image-map. An image-map is an image with clickable areas.

<img src="workplace.jpg" alt="Workplace" usemap="#workmap">

<map name="workmap">
	<area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.html">
	<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.html">
	<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.html">
</map>

- Shape

You must define the shape of the area, and you can choose one of these values:

  • rect - defines a rectangular region
  • circle - defines a circular region
  • poly - defines a polygonal region
  • default - defines the entire region

- Coordinates

You must define some coordinates to be able to place the clickable area onto the image.

The coordinates come in pairs, one for the x-axis and one for the y-axis.

The coordinates 34, 44 is located 34 pixels from the left margin and 44 pixels from the top.


Picture element

The picture element allows us to display different pictures for different devices or screen sizes.

The <picture> element contains a number of <source> elements, each referring to different image sources. This way the browser can choose the image that best fits the current view and/or device.

Each <source> element have attributes describing when their image is the most suitable.

Show different images on different screen sizes:

<picture>
	<source media="(min-width: 650px)" srcset="img_food.jpg">
	<source media="(min-width: 465px)" srcset="img_car.jpg">
	<img src="img_girl.jpg">
</picture>

Always specify an <img> element as the last child element of the <picture> element. The <img> element is used by browsers that do not support the <picture> element, or if none of the <source> tags matched.


Tables

  • Use the HTML <table> element to define a table
  • Use the HTML <tr> element to define a table row
  • Use the HTML <td> element to define a table data
  • Use the HTML <th> element to define a table heading
  • Use the HTML <caption> element to define a table caption
  • Use the CSS border property to define a border
  • Use the CSS border-collapse property to collapse cell borders
  • Use the CSS padding property to add padding to cells
  • Use the CSS text-align property to align cell text
  • Use the CSS border-spacing property to set the spacing between cells
  • Use the colspan attribute to make a cell span many columns
  • Use the rowspan attribute to make a cell span many rows
  • Use the id attribute to uniquely define one table

Lists

  • Use the HTML <ul> element to define an unordered list
  • Use the CSS list-style-type property to define the list item marker
  • Use the HTML <ol> element to define an ordered list
  • Use the HTML type attribute to define the numbering type
  • Use the HTML <li> element to define a list item
  • Use the HTML <dl> element to define a description list
  • Use the HTML <dt> element to define the description term
  • Use the HTML <dd> element to describe the term in a description list
  • Lists can be nested inside lists
  • List items can contain other HTML elements
  • Use the CSS property float:left or display:inline to display a list horizontally

Blocks

Every HTML element has a default display value depending on what type of element it is.

The two display values are: block and inline.

- Block-level elements

A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).

The <div> element is a block-level element.

- Inline elements

An inline element does not start on a new line and only takes up as much width as necessary.

The <span> element is a inline element.


File paths

A file path describes the location of a file in a web site's folder structure.

File paths are used when linking to external files like:

  • Web pages
  • Images
  • Style sheets
  • JavaScripts

- Absolute file paths

An absolute file path is the full URL to an internet file.

- Relative file paths

A relative file path points to a file relative to the current page.

- Best practice

It is best practice to use relative file paths (if possible).

When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.


Head

The <head> element is a container for metadata (data about data) and is placed between the <html> tag and the <body> tag.

HTML metadata is data about the HTML document. Metadata is not displayed.

Metadata typically define the document title, character set, styles, scripts, and other meta information.

The following tags describe metadata: <title>, <style>, <meta>, <link>, <script>, and <base>.

- <meta> element

The <meta> element is used to specify which character set is used, page description, keywords, author, and other metadata.

Metadata is used by browsers (how to display content), by search engines (keywords), and other web services.

Define the character set used:

<meta charset="UTF-8">

Define a description of your web page:

<meta name="description" content="Free Web tutorials">

Define keywords for search engines:

<meta name="keywords" content="HTML, CSS, XML, JavaScript">

Define the author of a page:

<meta name="author" content="John Doe">

Refresh document every 30 seconds:

<meta http-equiv="refresh" content="30">

Example of <meta> tags:

<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="John Doe">

- Setting the viewport

HTML5 introduced a method to let web designers take control over the viewport, through the <meta> tag.

The viewport is the user's visible area of a web page. It varies with the device, and will be smaller on a mobile phone than on a computer screen.

You should include the following <meta> viewport element in all your web pages:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

A <meta> viewport element gives the browser instructions on how to control the page's dimensions and scaling.

The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).

The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

- <base> element

The <base> element specifies the base URL and base target for all relative URLs in a page.

<base href="https://alishoff.com/images/" target="_blank">
  • <head> - Defines information about the document
  • <title> - Defines the title of a document
  • <base> - Defines a default address or a default target for all links on a page
  • <link> - Defines the relationship between a document and an external resource
  • <meta> - Defines metadata about an HTML document
  • <script> - Defines a client-side script
  • <style> - Defines style information for a document

Layout

There are five different ways to create multicolumn layouts. Each way has its pros and cons:

  • HTML tables (not recommended)
  • CSS float property
  • CSS flexbox
  • CSS framework
  • CSS grid

Computer code elements

  • <code> - Defines programming code
  • <kbd> - Defines keyboard input
  • <samp> - Defines computer output
  • <var> - Defines a variable
  • <pre> - Defines preformatted text

URL encode

A URL is another word for a web address.

A URL can be composed of words (w3schools.com), or an Internet Protocol (IP) address (192.68.20.50).

Most people enter the name when surfing, because names are easier to remember than numbers.

Web browsers request pages from web servers by using a URL.

A Uniform Resource Locator (URL) is used to address a document (or other data) on the web.

A web address like https://www.w3schools.com/html/default.asp follows these syntax rules:

scheme://prefix.domain:port/path/filename

Explanation:

  • scheme - defines the type of Internet service (most common is http or https)
  • prefix - defines a domain prefix (default for http is www)
  • domain - defines the Internet domain name (like w3schools.com)
  • port - defines the port number at the host (default for http is 80)
  • path - defines a path at the server (If omitted: the root directory of the site)
  • filename - defines the name of a document or resource

- Common URL schemes

  • http - Common web pages. Not encrypted
  • https - Secure web pages. Encrypted
  • ftp - Downloading or uploading files
  • file - A file on your computer

XHTML

XHTML is HTML written as XML.

  • XHTML stands for EXtensible HyperText Markup Language
  • XHTML is almost identical to HTML
  • XHTML is stricter than HTML
  • XHTML is HTML defined as an XML application
  • XHTML is supported by all major browsers

- The most important differences from HTML:

Document structure

  • XHTML DOCTYPE is mandatory
  • The xmlns attribute in <html> is mandatory
  • <html>, <head>, <title>, and <body> are mandatory

XHTML elements

  • XHTML elements must be properly nested
  • XHTML elements must always be closed
  • XHTML elements must be in lowercase
  • XHTML documents must have one root element

XHTML attributes

  • Attribute names must be in lower case
  • Attribute values must be quoted
  • Attribute minimization is forbidden

- How to convert from HTML to XHTML

  1. Add an XHTML <!DOCTYPE> to the first line of every page
  2. Add an xmlns attribute to the html element of every page
  3. Change all element names to lowercase
  4. Close all empty elements
  5. Change all attribute names to lowercase
  6. Quote all attribute values

Forms

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

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

- The method attribute

The method attribute specifies the HTTP method (GET or POST) to be used when submitting the form data.

When to use GET?

The default method when submitting form data is GET.

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

/action_page.php?firstname=Mickey&lastname=Mouse

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 submitted 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

- Here is the list of all <form> attributes:

  • accept-charset - Specifies the charset used in the submitted form (default: the page charset).
  • action - Specifies an address (url) where to submit the form (default: the submitting page).
  • 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: GET).
  • name - Specifies a name used to identify the form (for DOM usage: document.forms.name).
  • novalidate - Specifies that the browser should not validate the form.
  • target - Specifies the target of the address in the action attribute (default: _self).

- Form elements

  • <form> - Defines an HTML form for user input
  • <input> - Defines an input control
  • <textarea> - Defines a multiline input control (text area)
  • <label> - Defines a label for an <input> element
  • <fieldset> - Groups related elements in a form
  • <legend> - Defines a caption for a <fieldset> element
  • <select> - Defines a drop-down list
  • <optgroup> - Defines a group of related options in a drop-down list
  • <option> - Defines an option in a drop-down list
  • <button> - Defines a clickable button
  • <datalist> - Specifies a list of pre-defined options for input controls
  • <output> - Defines the result of a calculation

- 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">

- Here is a list of some common input restrictions:

  • checked - Specifies that an input field should be pre-selected when the page loads (for 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

HTML5

- 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">

- 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>.

- 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

- 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

History

Since the early days of the World Wide Web, there have been many versions of HTML:

  • 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

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.

- 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:

<!DOCTYPE html>
<html>
	<head>
		<script>document.createElement("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>

The JavaScript statement document.createElement("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.

Syntax

<head>
	<!--[if lt IE 9]>
		<script src="/js/html5shiv.js"></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:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<!--[if lt IE 9]>
			<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
		<![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>

HTML5 new elements

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:

  • <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 other text outside it
  • <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 typography)
  • <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

- New form elements

  • <datalist> - Specifies a list of pre-defined options for input controls
  • <output> - Defines the result of a calculation

- New input types

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week

- New input attributes

  • autocomplete
  • autofocus
  • form
  • formaction
  • formenctype
  • formmethod
  • formnovalidate
  • formtarget
  • height and width
  • list
  • min and max
  • multiple
  • pattern (regexp)
  • placeholder
  • required
  • step

- 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'>

- HTML5 graphics

  • <canvas> - Draw graphics, on the fly, via scripting (usually JavaScript)
  • <svg> - Draw scalable vector graphics

- New media elements

  • <audio> - Defines sound content
  • <embed> - Defines a container for an external (non-HTML) application
  • <source> - Defines multiple media resources for media elements (<video> and <audio>)
  • <track> - Defines text tracks for media elements (<video> and <audio>)
  • <video> - Defines video or movie

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.

- 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.

- Draw a line

<!DOCTYPE html>
<html>
	<body>
		<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
			Your browser does not support the HTML5 canvas tag.
		</canvas>

		<script>
			var c = document.getElementById("myCanvas");
			var ctx = c.getContext("2d");
			
			ctx.moveTo(0,0);
			ctx.lineTo(200,100);
			ctx.stroke();
		</script>
	</body>
</html>

- Draw a circle

<!DOCTYPE html>
<html>
	<body>
		<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
			Your browser does not support the HTML5 canvas tag.
		</canvas>

		<script>
			var c = document.getElementById("myCanvas");
			var ctx = c.getContext("2d");
			
			ctx.beginPath();
			ctx.arc(95,50,40,0,2*Math.PI);
			ctx.stroke();
		</script> 
	</body>
</html>

- Draw a Text

<!DOCTYPE html>
<html>
	<body>
		<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
			Your browser does not support the HTML5 canvas tag.
		</canvas>

		<script>
			var c = document.getElementById("myCanvas");
			var ctx = c.getContext("2d");
			
			ctx.font = "30px Arial";
			ctx.fillText("Hello World",10,50);
		</script>
	</body>
</html>

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 is a container for SVG graphics.

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

- Circle

<!DOCTYPE html>
<html>
	<body>
		<svg width="100" height="100">
			<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
			Sorry, your browser does not support inline SVG.
		</svg>
	</body>
</html>

- Rectangle

<!DOCTYPE html>
<html>
	<body>
		<svg width="400" height="100">
			<rect width="400" height="100" style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" />
			Sorry, your browser does not support inline SVG.
		</svg>
	</body>
</html>

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

Canvas

  • Resolution dependent
  • No support for event handlers
  • Poor text rendering capabilities
  • You can save the resulting image as .png or .jpg
  • Well suited for graphic-intensive games

SVG

  • Resolution independent
  • Support for event handlers
  • Best suited for applications with large rendering areas (Google Maps)
  • Slow rendering if complex (anything that uses the DOM a lot will be slow)
  • Not suited for game applications

Multimedia

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

- 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.

  • 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.

- Video formats:

  • Format - File - Description
  • MPEG - .mpg, .mpeg - MPEG. Developed by the Moving Pictures Expert Group. The first popular video format on the web. Used to be supported by all browsers, but it is not supported in HTML5.
  • AVI - .avi - AVI (Audio Video Interleave). Developed by Microsoft. Commonly used in video cameras and TV hardware. Plays well on Windows computers, but not in web browsers.
  • WMV - .wmv - WMV (Windows Media Video). Developed by Microsoft. Commonly used in video cameras and TV hardware. Plays well on Windows computers, but not in web browsers.
  • QuickTime - .mov - QuickTime. Developed by Apple. Commonly used in video cameras and TV hardware. Plays well on Apple computers, but not in web browsers.
  • RealVideo - .rm, .ram - RealVideo. Developed by Real Media to allow video streaming with low bandwidths. It is still used for online video and Internet TV, but does not play in web browsers.
  • Flash - .swf, .flv - Flash. Developed by Macromedia. Often requires an extra component (plug-in) to play in web browsers.
  • Ogg - .ogg - Theora Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5.
  • WebM - .webm - WebM. Developed by the web giants, Mozilla, Opera, Adobe, and Google. Supported by HTML5.
  • MPEG-4 or MP4 - .mp4 - MP4. Developed by the Moving Pictures Expert Group. Based on QuickTime. Commonly used in newer video cameras and TV hardware. Supported by all HTML5 browsers. Recommended by YouTube.

Only MP4, WebM, and Ogg video are supported by the HTML5 standard.

- Audio formats:

  • Format - File - Description
  • MIDI - .mid, .midi - MIDI (Musical Instrument Digital Interface). Main format for all electronic music devices like synthesizers and PC sound cards. MIDI files do not contain sound, but digital notes that can be played by electronics. Plays well on all computers and music hardware, but not in web browsers.
  • RealAudio - .rm, .ram - RealAudio. Developed by Real Media to allow streaming of audio with low bandwidths. Does not play in web browsers.
  • WMA - .wma - WMA (Windows Media Audio). Developed by Microsoft. Commonly used in music players. Plays well on Windows computers, but not in web browsers.
  • AAC - .aac - AAC (Advanced Audio Coding). Developed by Apple as the default format for iTunes. Plays well on Apple computers, but not in web browsers.
  • WAV - .wav - WAV. Developed by IBM and Microsoft. Plays well on Windows, Macintosh, and Linux operating systems. Supported by HTML5.
  • Ogg - .ogg - Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5.
  • MP3 - .mp3 - MP3 files are actually the sound part of MPEG files. MP3 is the most popular format for music players. Combines good compression (small files) with high quality. Supported by all browsers.
  • MP4 - .mp4 - MP4 is a video format, but can also be used for audio. MP4 video is the upcoming video format on the internet. This leads to automatic support for MP4 audio by all browsers.

Only MP3, WAV, and Ogg audio are supported by the HTML5 standard.


Video

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.

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

<!DOCTYPE html>
<html>
	<body>
		<video width="320" height="240" controls>
			<source src="movie.mp4" type="video/mp4">
			<source src="movie.ogg" type="video/ogg">
			Your browser does not support the video tag.
		</video>
	</body>
</html>

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.

To start a video automatically use the autoplay attribute:

<!DOCTYPE html>
<html>
	<body>
		<video width="320" height="240" autoplay>
			<source src="movie.mp4" type="video/mp4">
			<source src="movie.ogg" type="video/ogg">
			Your browser does not support the video tag.
		</video>

		<p><b>Note:</b> The autoplay attribute does not work on some mobile devices.</p>
	</body>
</html>

- Media types

  • MP4 - video/mp4
  • WebM - video/webm
  • Ogg - video/ogg

- 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.

<!DOCTYPE html> 
<html> 
	<body> 
		<div style="text-align:center"> 
			<button onclick="playPause()">Play/Pause</button> 
			<button onclick="makeBig()">Big</button>
			<button onclick="makeSmall()">Small</button>
			<button onclick="makeNormal()">Normal</button>
			<br><br>
			
			<video id="video" width="420">
				<source src="mov_bbb.mp4" type="video/mp4">
				<source src="mov_bbb.ogg" type="video/ogg">
				Your browser does not support HTML5 video.
			</video>
		</div> 

		<script> 
			var myVideo = document.getElementById("video"); 

			function playPause() {
				if (myVideo.paused) {
					myVideo.play();
				} else {
					myVideo.pause(); 
				}
			} 

			function makeBig() { 
				myVideo.width = 560; 
			} 

			function makeSmall() { 
				myVideo.width = 320; 
			} 

			function makeNormal() { 
				myVideo.width = 420; 
			} 
		</script>
	</body> 
</html>

Audio

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.

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

<!DOCTYPE html>
<html>
	<body>
		<audio controls>
			<source src="horse.ogg" type="audio/ogg">
			<source src="horse.mp3" type="audio/mpeg">
			Your browser does not support the audio element.
		</audio>
	</body>
</html>

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.

- Media types

  • MP3 - audio/mpeg
  • OGG - audio/ogg
  • WAV - audio/wav

- 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.


Geolocation

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.

- 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:

<!DOCTYPE html>
<html>
	<body>
		<p>Click the button to get your coordinates.</p>

		<button onclick="getLocation()">Try It</button>

		<p id="demo"></p>

		<script>
			var x = document.getElementById("demo");

			function getLocation() {
				if (navigator.geolocation) {
					navigator.geolocation.getCurrentPosition(showPosition);
				} else { 
					x.innerHTML = "Geolocation is not supported by this browser.";
				}
			}

			function showPosition(position) {
				x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
			}
		</script>
	</body>
</html>

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:

<!DOCTYPE html>
<html>
	<body>
		<p>Click the button to get your coordinates.</p>

		<button onclick="getLocation()">Try It</button>

		<p id="demo"></p>

		<script>
			var x = document.getElementById("demo");

			function getLocation() {
				if (navigator.geolocation) {
					navigator.geolocation.getCurrentPosition(showPosition, showError);
				} else { 
					x.innerHTML = "Geolocation is not supported by this browser.";
				}
			}

			function showPosition(position) {
				x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
			}

			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;
				}
			}
		</script>
	</body>
</html>

- 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):

function showPosition(position) {
	var latlon = position.coords.latitude + "," + position.coords.longitude;

	var img_url = "https://maps.googleapis.com/maps/api/staticmap?center="+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";

	document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

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

  • coords.latitude - The latitude as a decimal number (always returned)
  • coords.longitude - The longitude as a decimal number (always returned)
  • coords.accuracy - The accuracy of position (always returned)
  • coords.altitude - The altitude in meters above the mean sea level (returned if available)
  • coords.altitudeAccuracy - The altitude accuracy of position (returned if available)
  • coords.heading - The heading as degrees clockwise from North (returned if available)
  • coords.speed - The speed in meters per second (returned if available)
  • timestamp - The date/time of the response (returned if available)

- Geolocation Object - 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.

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.

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>
		<p>Drag the W3Schools image into the rectangle:</p>

		<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>

- 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 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:

event.preventDefault()

- 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)
  • Get the dragged data with the dataTransfer.getData() 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

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.

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

  • window.localStorage - stores data with no expiration date
  • window.sessionStorage - 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.

<!DOCTYPE html>
<html>
	<body>
		<div id="result"></div>

		<script>
			// Check browser support
			if (typeof(Storage) !== "undefined") {
				// Store
				localStorage.setItem("lastname", "Smith");
				
				// Retrieve
				document.getElementById("result").innerHTML = localStorage.getItem("lastname");
			} else {
				document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
			}
		</script>
	</body>
</html>

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
localStorage.lastname = "Smith";

// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

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

localStorage.removeItem("lastname");

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

<!DOCTYPE html>
<html>
	<head>
		<script>
			function clickCounter() {
				if (typeof(Storage) !== "undefined") {
					if (localStorage.clickcount) {
						localStorage.clickcount = Number(localStorage.clickcount)+1;
					} else {
						localStorage.clickcount = 1;
					}
					
					document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
				} else {
					document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
				}
			}
		</script>
	</head>
	<body>
		<p><button onclick="clickCounter()" type="button">Click me!</button></p>
		<div id="result"></div>
		
		<p>Click the button to see the counter increase.</p>
		<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
	</body>
</html>

- 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:

<!DOCTYPE html>
<html>
	<head>
		<script>
			function clickCounter() {
				if (typeof(Storage) !== "undefined") {
					if (sessionStorage.clickcount) {
						sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
					} else {
						sessionStorage.clickcount = 1;
					}
					
					document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
				} else {
					document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
				}
			}
		</script>
	</head>
	<body>
		<p><button onclick="clickCounter()" type="button">Click me!</button></p>
		<div id="result"></div>
		
		<p>Click the button to see the counter increase.</p>
		<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
	</body>
</html>

Web workers

A web worker is a JavaScript running in the background, without affecting the performance of the page.

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.

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

<!DOCTYPE html>
<html>
	<body>
		<p>Count numbers: <output id="result"></output></p>
		
		<button onclick="startWorker()">Start Worker</button> 
		<button onclick="stopWorker()">Stop Worker</button>

		<p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p>

		<script>
			var w;

			function startWorker() {
				if(typeof(Worker) !== "undefined") {
					if(typeof(w) == "undefined") {
						w = new Worker("demo_workers.js");
					}
					
					w.onmessage = function(event) {
						document.getElementById("result").innerHTML = event.data;
					};
				} else {
					document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
				}
			}

			function stopWorker() { 
				w.terminate();
				w = undefined;
			}
		</script>
	</body>
</html>

- 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.

w.onmessage = function(event) {
	document.getElementById("result").innerHTML = event.data;
};

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

- 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:

w.terminate();

- Reuse the web worker

If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

- Web workers and the DOM

Since web workers are in external files, they do not have access to the following JavaScript objects:

  • The window object
  • The document object
  • The parent object

SSE - Server-Sent Events

Server-Sent Events allow a web page to get updates from a server.

A server-sent event is when a web page automatically gets updates from a server.

This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.

- Receive Server-Sent Event notifications

The EventSource object is used to receive server-sent event notifications:

<!DOCTYPE html>
<html>
	<body>
		<h1>Getting server updates</h1>
		
		<div id="result"></div>

		<script>
			if(typeof(EventSource) !== "undefined") {
				var source = new EventSource("demo_sse.php");
				
				source.onmessage = function(event) {
					document.getElementById("result").innerHTML += event.data + "<br>";
				};
			} else {
				document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
			}
		</script>
	</body>
</html>

Example explained:

  • Create a new EventSource object, and specify the URL of the page sending the updates (in this example "demo_sse.php")
  • Each time an update is received, the onmessage event occurs
  • When an onmessage event occurs, put the received data into the element with id="result"

- Check Server-Sent Events support

if(typeof(EventSource) !== "undefined") {
	// Yes! Server-sent events support!
	// Some code.....
} else {
	// Sorry! No server-sent events support..
}

- Server-Side code example

For the example above to work, you need a server capable of sending data updates (like 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.

Code in PHP (demo_sse.php):

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";

flush();

Code explained:

  • Set the "Content-Type" header to "text/event-stream"
  • Specify that the page should not cache
  • Output the data to send (Always start with "data: ")
  • Flush the output data back to the web page

- The EventSource object

In the examples above we used the onmessage event to get messages. But other events are also available:

  • onopen - When a connection to the server is opened
  • onmessage - When a message is received
  • onerror - When an error occurs