The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by haxohaw528, 2022-05-15 03:00:05

CS 202 Updated Handouts Of VU

CS 202 Updated Handouts Of VU

Keywords: CS 202 Updated Handouts Of VU,vu handouts,vuassist

JSON.parse()
The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript
object.

var obj = JSON.parse(text);
Old Browsers

var obj = eval ("(" + text + ")");

HTML5

Introduction
HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It is
the fifth and current version of the HTML standard. HTML5 includes detailed processing models to
encourage more interoperable implementations; it extends, improves and rationalizes the markup
available for documents, and introduces markup and application programming interfaces (APIs) for
complex web applications. HTML5 is the latest version of HTML, latest take a look on HTML History.
Since the early days of the web, there have been many versions of HTML:

1989

WordlWideWeb invented by Tim Berners Lee.
1991
HTML invented by Tim Berners Lee
1993
HTML+ drafted by Dave Raggett
1995
HTML Working Group define HTML 2.0
1997
W3C Recommended HTML 3.2
1999
W3C Recommended HTML 4.01
2000
W3C Recommended XHTML 1.0
2004
WHATWG (Web Hypertext Application Technology Working Group) Formed.
2008
HTML5 WHATWG (Web Hypertext Application Technology Working Group) First Public Draft
2012
HTML5 WHATWG Living Standard
2014
HTML5 W3C Final Recommendation
HTML5
HTML5 is an enhanced version of HTML. It was published by W3C on 28 October 2014.
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">
See here HTML5 document example:

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
Content of the document......
</body>
</html>

New HTML5 Elements

The most interesting new elements are:

 New semantic elements like <header>, <footer>, <article>, and <section>.
 New form control attributes like number, date, time, calendar, and range.

The most interesting new elements are:

 New graphic elements: <svg> and <canvas>.
 New multimedia elements: <audio> and <video>.

New HTML5 API's (Application Programming Interfaces): HTML5 offers some set of APIs,

The most interesting new API's are:

 HTML Geolocation
 HTML Drag and Drop
 HTML Local Storage
 HTML Application Cache
 HTML Web Workers
 HTML SSE (Server Sent Events)

Elements Removed in HTML5

Some HTML4 Elements are also removed in HTML5.

Element Replaced With

<acronym> <abbr>

<applet> <object>
<basefont> CSS
<big> CSS
<center> CSS
<dir> <ul>
Element Replaced With
<font> CSS
<frame>
<frameset> CSS
<noframes> CSS
<strike>
<tt>

New Elements in HTML5
Many new Elements introduced in HTML5, for better document structure. see here, some of new
elements added in HTML5:

Tag Description

<article> Defines an article in the document

<aside> Defines content aside from the page content

<bdi> Defines a part of text that might be formatted in a different direction from other text
<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, like illustrations, diagrams, photos, code listings, etc.

<footer> Defines a footer for the document or a section

<header> Defines a header for the document or a section
<main> Defines the main content of a document

<mark> Defines marked or highlighted text
<menuitem> Defines a command/menu item that the user can invoke from a popup menu
<meter> Defines a scalar measurement within a known range (a gauge)

<nav> Defines navigation links in the document

<progress> Defines the progress of a task
<mark> Defines marked or highlighted text
<menuitem> Defines a command/menu item that the user can invoke from a popup menu
<meter> Defines a scalar measurement within a known range (a gauge)

<nav> Defines navigation links in the document
<progress> Defines 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 the document
<summary> Defines a visible heading for a <details> element
<time> Defines a date/time
<wbr> Defines a possible line-break

New Form Elements
Tag Description

<datalist> Defines pre-defined options for input controls

<keygen> Defines a key-pair generator field (for forms)

<output> Defines the result of a calculation

New Input Types New Input Attributes
New Input Types

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

HTML5 - New Attribute Syntax
HTML5 allows four different syntaxes for attributes.

HTML5 - New Attribute Syntax
• 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

Tag Description

<canvas> Defines graphic drawing using JavaScript

<svg> Defines graphic drawing using SVG

New Media Elements Description
Tag

<audio> Defines sound or music content

<embed> Defines containers for external applications (like plug-ins)

<source> Defines sources for <video> and <audio>
<track> Defines tracks for <video> and <audio>
<video> Defines video or movie content

128- HTML5 Semantics
What are Semantic Elements?
A semantic element clearly describes its meaning to both the browser and the developer.
Semantics is the study of the meanings of words and phrases in language. Semantic elements are
elements with a meaning.
Examples of non-semantic elements:
<div> and <span>
Examples of semantic elements:
<form>, <table>, and <img>
It’s common to use HTML code like:
<div id="nav">
<div class="header">
<div id="footer">
These are used to indicate the navigation, header, and footer in HTML5 document.
HTML5 offers new semantic elements to define different parts of a web page.

Here are some new Semantic Elements in HTML5:

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

According to W3C's HTML5 documentation:

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

A Web site's home page could be split into sections for introduction, content, and contact
information.

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

See the following example:

<article>

<h1>Heading</h1>

<p>Lorem ipsum dolor sit amet</p>

<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur.</p>

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

HTML5 <footer> Element

The <footer> element specifies footer for a document or section. A <footer> element should
contain information about its containing element.

HTML5 <nav> Element

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

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.

HTML5 <figure> and <figcaption> Elements

In books and newspapers, it is common to have captions with images. With HTML5, images and
captions can be grouped together in <figure> elements.

Why Semantic HTML5 Elements?

With HTML4, developers used their own favorite attribute names to style page elements:

header, top, bottom, footer, menu, navigation, main, container, content, article, sidebar, topnav,


Why Semantic HTML5 Elements?

This made it impossible for search engines to identify the correct web page content. With
HTML5 elements like: <header> <footer> <nav> <section> <article>, this will become easier to
identify.

According to the W3C, a Semantic Web:

"Allows data to be shared and reused across applications, enterprises, and communities."

129- HTML4 to HTML5 Migration

Migration from HTML4 to HTML5

Let see how to convert an existing HTML4 page into an HTML5 page, without destroying anything of the
original content or structure.

Typical HTML4 Typical HTML5

<div id="header"> <header>

<div id="menu"> <nav>

<div id="content"> <section>

<div id="post"> <article>

<div id="footer"> <footer>

Change to HTML5 Doctype Transitional//EN"
HTML4 doctype:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
"http://www.w3.org/TR/html4/loose.dtd">
HTML5 doctype:
<!DOCTYPE html>
HTML4:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

HTML5:
<meta charset="utf-8">
Browser Support
HTML5 semantic elements are supported in all modern browsers. In addition, you can "teach" older
browsers how to handle "unknown elements".
For Internet Explorer support:
<!--[if lt IE 9]>

<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
Add CSS for HTML5 Semantic Elements
Review your existing CSS styles
Existing CSS styles:

div#header,div#footer,div#content,div#post {
border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-

color:white;
}
div#header,div#footer {

color:white;background-color:#444;margin-bottom:5px;
}
div#content {

background-color:#ddd;
}
div#menu ul {

margin:0;padding:0;
}
div#menu ul li {

display:inline; margin:5px;
}
Add CSS for HTML5 Semantic Elements

Duplicate with equal CSS styles for HTML5 semantic elements.
CSS for HTML5

header,footer,section,article {
border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-

color:white;
}
header,footer {

color:white;background-color:#444;margin-bottom:5px;
}
section {

background-color:#ddd;
}
nav ul {

margin:0;padding:0;
}
nav ul li {

display:inline; margin:5px;
}
Change to HTML5 <header> and <footer>
Change the <div> elements with id="header" and id="footer" to HTML5 semantic <header> and
<footer> elements

<div id="header">
<h1>Monday Times</h1>
</div>
.
.
<div id="footer">
<p>&amp;copy; 2015 SomeSite. All rights reserved.</p>
</div>

<h1>Monday Times</h1>
</header>
.
.
<footer>
<p>&copy; 2014 W3Schools. All rights reserved.</p>
</footer>
Change to HTML5 <nav>
Change the <div> element with id="menu" to an HTML5 semantic <nav> element.
<div id="menu">
<ul>

<li>News</li>
<li>Sports</li>
<li>Weather</li>
</ul>
</div>

<nav>
<ul>
<li>News</li>
<li>Sports</li>
<li>Weather</li>
</ul>

</nav>

Change to HTML5 <section>
Change the <div> element with id="content" to an HTML5 semantic <section> element.

<div id="content“>
….
</div>
<section>
….
</section>
Change to HTML5 <article>
Change all <div> element with class="post" to HTML5 semantic <article> elements.
<div class="post">

<h2>News Article</h2>
<p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum
turum ipsum
lurum hurum turum.</p>
</div>
<article>
<h2>News Article</h2>
<p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum
turum ipsum
lurum hurum turum.</p>
</article>
<head> Tag
Finally you can remove the <head> tags. They are not needed in HTML5.
130a- HTML5 Coding Conventions
No certain coding style and syntax to use in HTML. With XHTML, developers were forced to write valid
and "well-formed" code.
HTML5 is a bit sloppier when it comes to code validation. With HTML5, you must create your own Best
Practice, Style Guide and Coding Conventions.
Be Smart and Future Proof
Keep a consistent style is the key. Using a well-formed "close to XHTML" syntax, can be smart.
Correct Document Type
Always declare the document type as the first line in your document:

<!DOCTYPE html>
If you want consistency with lower case tags, you can use:
<!doctype html>
Use Lower Case Element Names
HTML5 allows mixing uppercase and lowercase letters in element names. We recommend using
lowercase element names.

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

<Section>
<p>This is a paragraph.</p>
</SECTION>
<section>
<p>This is a paragraph.</p>
</section>
Close All HTML Elements
In HTML5, you don't have to close all elements (for example the <p> element). We recommend
closing all HTML elements.
Close All HTML Elements
Looking bad:
<section>
<p>This is a paragraph.
<p>This is a paragraph.
</section>

Looking good:
<section>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>

</section>
Close Empty HTML Elements

In HTML5, it is optional to close empty elements.
This is allowed:
<meta charset="utf-8">
This is also allowed:
<meta charset="utf-8" />
The slash (/) is required in XHTML and XML.
Use Lower Case Attribute Names
HTML5 allows mixing uppercase and lowercase letters in attribute names. We recommend using
lowercase attribute names.
<div CLASS="menu">
<div class="menu">
Quote Attribute Values
HTML5 allows attribute values without quotes. We recommend quoting attribute values.
This will not work, because the value contains spaces:
<table class=table striped>
This will work:
<table class="table striped">
Not good to mix style, so better to always use quotes.
Image Attributes
Always use the alt attribute with images. It is important when the image cannot be viewed.
<img src="html5.gif" alt="HTML5" style="width:128px;height:128px“>
Always define image size. It reduces flickering because the browser can reserve space for images
before they are loaded.
<img src="html5.gif" alt="HTML5“ style="width:128px;height:128px">
130b- HTML5 Coding Conventions
Avoid Long Code Lines
When using an HTML editor, it is inconvenient to scroll right and left to read the HTML code.
Try to avoid code lines longer than 80 characters.

Spaces and Equal Signs
Spaces around equal signs is legal:

<link rel = "stylesheet" href = "styles.css">
But space-less is easier to read, and groups entities better together:

<link rel="stylesheet" href="styles.css">
Blank Lines and Indentation
Do not add blank lines without a reason. For readability, add blank lines to separate large or
logical code blocks. For readability, add 2 spaces of indentation. Do not use TAB.
Blank Lines and Indentation
Do not use unnecessary blank lines and indentation. It is not necessary to use blank lines between
short and related items. It is not necessary to indent every element.
Omitting <html> and <body>?
In the HTML5 standard, the <html> tag and the <body> tag can be omitted.

<!DOCTYPE html>
<head>
<title>Page Title</title>
</head>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
We do not recommend omitting the <html> and <body> tags.
<html> element is the root.
Declaring a language is important for accessibility applications (screen readers) and search
engines. Possible in <html> element.
Omitting <head>?
In the HTML5 standard, the <head> tag can also be omitted. By default, browsers will add all
elements before <body>, to a default <head> element.
<!DOCTYPE html>
<html>

<title>Page Title</title>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Meta Data
The <title> element is required in HTML5. Make the title as meaningful as possible. To ensure
proper interpretation, and correct search engine indexing, both the language and the character
encoding should be defined as early as possible in a document:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>My Page Title</title>
</head>
HTML Comments
Short comments should be written on one line, with a space after <!-- and a space before -->:
<!-- This is a comment -->
Long comments, spanning many lines, should be written with <!-- and --> on separate lines:
<!--
This is a long comment example. This is a long comment example. This is a long comment
example.
This is a long comment example. This is a long comment example. This is a long comment
example.
-->
Long comments are easier to observe, if they are indented 2 spaces.
Loading Style Sheets
Use simple syntax for linking style sheets (the type attribute is not necessary).
<link rel="stylesheet" href="styles.css">
Loading JavaScript
Use simple syntax for loading external scripts (the type attribute is not necessary).

<script src="myscript.js">

Use Lower Case File Names

Most web servers (Apache, Unix) are case sensitive about file names. Other web servers
(Microsoft, IIS) are not case sensitive. If you move from a case insensitive, to a case sensitive
server, even small errors will break your web. To avoid these problems, always use lower case
file names (if possible).

Use Lower Case File Names

If you move from a case insensitive, to a case sensitive server, even small errors will break your
web. To avoid these problems, always use lower case file names (if possible).

131- HTML5 Canvas

What is HTML Canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The
<canvas> element is only a container for graphics. You must use a script to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, 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.

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

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.

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

</canvas>

Drawing on a Canvas

 Find the Canvas
 Create drawing object
 Draw on canvas

var can = document.getElementById("myCanvas");

Create a Drawing Object

var can = document.getElementById("myCanvas");

var ctx = can.getContext("2d");

Draw on Canvas

var can = document.getElementById("myCanvas");

var ctx = can.getContext("2d");

ctx.fillStyle = "#00FF00";
ctx.fillRect(0,0,200,100);
fillStyle()
Can be a CSS color, gradient or a pattern.
Drawing a Rectangle
fillRect(x,y,width,height)
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,200,100);
</script>
132- HTML5 Canvas Coordinates
Canvas Coordinates
The HTML canvas is a two-dimensional grid. The upper-left corner of the canvas has the
coordinates (0,0)
Draw a Line
Move Current position to starting point. Draw line to a specific point. Use an ink method to
display line in canvas.
moveTo(x,y) - defines the starting point of the line
lineTo(x,y) - defines the ending point of the line
stroke() - display line in canvas

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
133- HTML5 Canvas Gradients

Canvas Gradients
Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not
limited to solid colors.
Draw Gradients
There are two different types of gradients:

Linear
createLinearGradient(x,y,x1,y1)
Radial/Circular
createRadialGradient(x,y,r,x1,y1,r1)
Once we have a gradient object, we must add two or more color stops.
addColorStop()

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

addColorStop(pos,color);
Draw Linear Gradient

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"yellow");
grd.addColorStop(1,"blue");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
Draw Circular Gradient
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient

var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(0,0,200,80);
134- HTML5 Canvas Text
Drawing Text
You can draw text on canvas too with a specified fonts and style. 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)

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText “Some text",10,50 ;
Stroke Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText “Some text",10,50 ;
136- HTML5 SVG
SVG
 SVG stands for Scalable Vector Graphics
 SVG is used to define graphics for the Web
 SVG is a W3C recommendation
The HTML5 <svg> Element

The <svg> element is a container for SVG graphics. SVG has several methods for drawing paths,
boxes, circles, text, and graphic images.
SVG Circle

<!DOCTYPE html>
<html>
<body>
<svg width="500" height="500">
<circle cx="200" cy="200" r="100"
stroke="blue" stroke-width="5" fill="yellow" />
</svg>
</body>
</html>
SVG Rectangle
<svg width="400" height="100">
<rect x="100" y="100" width="300" height="100" style="fill:rgb(0,0,255);stroke-
width:1;stroke:rgb(0,0,0)" />
</svg>
SVG Rounded Rectangle
<svg width="400" height="100">
<rect x="100" y="100" rx="20" ry="20" width="300" height="100"
style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" />
</svg>
SVG Polygon
<svg width="400" height="100">

<polygon points="100,50 150,50 150,150 100,10"
style="fill:lime;stroke:red;stroke-width:5;fill-rule:evenodd;" />
</svg>
SVG Star using Polygon
<svg width="400" height="100">
<polygon points="100,10 40,198 190,78 10,78 160,198"

style="fill:lime;stroke:green;stroke-width:5;fill-rule:evenodd;" />

</svg>

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.

Canvas SVG Resolution independent
• Resolution dependent • Support for event handlers
• No support for event handlers • Best suited for applications with large
• Poor text rendering capabilities • rendering areas (Google Maps)
• You can save the resulting image as Slow rendering if complex (anything
• that uses the DOM a lot will be slow)
.png or .jpg Not suited for game applications
• Well suited for graphic-intensive •

games

137- HTML5 Media

HTML5 Multimedia

What is Multimedia?

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

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

Browser Support
 text only, single color.
 colors, fonts and pictures.
 sounds, animations, and videos

HTML5 multimedia promises an easier future for multimedia.

Multimedia Formats

Multimedia elements (like sounds or videos) are stored in media files. The most common way to
discover the type of a file, is to look at the file extension.

Video Formats

HTML5 standard support MP4, WebM, Ogg video formats

Format Description

Ogg Theora Ogg. Developed by the Xiph.Org Foundation.
.ogg

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

MPEG-4 By the Moving Pictures Expert Group. Based on QuickTime.
or MP4 Commonly used in newer video cameras and TV hardware.
.mp4

Audio Formats
HTML5 standard support MP3, WAV, Ogg audio formats.

Format Description

WAV By IBM and Microsoft. Plays well on Win, Mac, and Linux
.wav operating systems.

Ogg .ogg Ogg. By the Xiph.Org Foundation.

MP3 MP3 files are actually the sound part of MPEG files. most
.mp3 popular. Combines good compression (small files) with high
quality.

138- HTML5 Video

Playing Videos in HTML

Before HTML5, there was no standard for showing videos on a web page, and the videos could only be
played with a plug-in (like flash). The HTML5 <video> element specifies a standard way to embed a
video in a web page. See the following example:

<video width="320" height="240" controls>

<source src="movie.mp4" type="video/mp4">

<source src="movie.ogg" type="video/ogg">

Your browser does not support the video tag.

</video>

In the above example,

 The controls attribute adds video controls, like play, pause, and volume.
 Width and Height are optional but recommended.
 Text between the <video> and </video> tags will only display in browsers that do not

support the <video> element.
 Multiple <source> elements can link to different video files. The browser will use the

first recognized format.

HTML <video> Autoplay

To start a video automatically use the autoplay attribute

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

Note: Does not work on iPad and iPhone.

HTML Video - Browser Support

Currently, there are 3 supported video formats for the <video> element: MP4, WebM, and 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.

Method Description

addTextTrack() Adds a new text track to the audio/video
canPlayType() Checks if the browser can play the specified audio/video type
load() Re-loads the audio/video element
play() Starts playing the audio/video
pause() Pauses the currently playing audio/video

HTML5 Some Video Properties

Property Description
autoplay
Sets or returns whether the audio/video should start playing as soon as it is
currentTime loaded

duration Sets or returns the current playback position in the audio/video (in
ended seconds)
loop
Returns the length of the current audio/video (in seconds)
volume
Returns whether the playback of the audio/video has ended or not

Sets or returns whether the audio/video should start over again when
finished

Sets or returns the volume of the audio/video

HTML Video - Methods, Properties, and Events
There are also DOM events that can notify you when a video begins to play, is paused, etc.

HTML5 Some Video Events

Event Description

ended Fires when the current playlist is ended

error Fires when an error occurred during the loading of an audio/video

loadeddata Fires when the browser has loaded the current frame of the audio/video

pause Fires when the audio/video has been paused

play Fires when the audio/video has been started or is no longer paused

seeked Fires when the user is finished moving/skipping to a new position in the
audio/video

seeking Fires when the user starts moving/skipping to a new position in the
audio/video

volumechange when the volume has been changed

139- HTML5 Audio
Audio on the Web

Before HTML5, there was no standard for playing audio files on a web page and the audio files could
only be played with a plug-in (like flash).
The HTML5 <audio> element specifies a standard way to embed audio in a web page.

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

<audio controls>
<source src="sound.ogg" type="audio/ogg">
<source src="sound.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
HTML Audio - Browser Support
Currently, there are 3 supported file formats for the <audio> element: MP3, Wav, and Ogg.
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 setting duration and volume.

Method Description

addTextTrack() Adds a new text track to the audio/video

canPlayType() Checks if the browser can play the specified
audio/video type

load() Re-loads the audio/video element

play() Starts playing the audio/video

pause() Pauses the currently playing audio/video

HTML5 Some Audio Properties

Property Description

autoplay Sets or returns whether the audio/video should start playing as soon
as it is loaded

currentTime Sets or returns the current playback position in the audio/video (in
seconds)
duration
ended Returns the length of the current audio/video (in seconds)
loop
Returns whether the playback of the audio/video has ended or not
volume
Sets or returns whether the audio/video should start over again
when finished

Sets or returns the volume of the audio/video

HTML Audio - Methods, Properties, and Events
There are also DOM events that can notify you when an audio begins to play, is paused, etc.

HTML5 Some Audio Events

Event Description

ended Fires when the current playlist is ended

error Fires when an error occurred during the loading of an audio/video

loadeddata Fires when the browser has loaded the current frame of the audio/video

pause Fires when the audio/video has been paused

play Fires when the audio/video has been started or is no longer paused

seeked Fires when the user is finished moving/skipping to a new position in
the audio/video

seeking Fires when the user starts moving/skipping to a new position in the
audio/video

volumechange when the volume has been changed

140- HTML5 Plug-ins

HTML Helpers

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

HTML Plug-ins

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.

<object width="100px" height="500px" data=“example.swf"></object>

<object width="100%" height="500px" data="snippet.html"></object>
<object data=“animage.jpeg"></object>

The <embed> Element
The <embed> element is also 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. But it’s not a part of HTML
specification before HTML5.

<embed width="400" height="50" src="bookmark.swf">

<embed width="100%" height="500px" src="snippet.html">
<embed src=“animage.jpeg">

141- HTML5 Geolocation

Locate the User's Position
The HTML Geolocation API is used to get the geographical position of a user. Since this can
compromise user privacy, the position is not available unless the user approves it.

Geolocation is much more accurate for devices with GPS, like iPhone.

Using HTML Geolocation

Use the getCurrentPosition() method to get the user's position.

Example:

navigator.geolocation.

getCurrentPosition(showPosition);

function showPosition(position) {

str = "Latitude: " +

position.coords.latitude +

"<br>Longitude: " +

position.coords.longitude;
}

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.
See the following example:

navigator.geolocation.
getCurrentPosition(showPosition, showError);
Here is another example:
function showError(error) {

switch(error.code) {
case error.PERMISSION_DENIED: break;
case error.POSITION_UNAVAILABLE: break;
case error.TIMEOUT: break;
case error.UNKNOWN_ERROR: break;

}
}
Displaying the Result in a Map
To display the result in a map, you need access to a map service that can use latitude and
longitude, like Google Maps. See the example below:
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=" + langitude
+","+ longitude + "&zoom=14&size=400x300&sensor=false";
Location-specific Information
Geolocation is also very useful for location-specific information.
 Up-to-date local information
 Showing Points-of-interest near the user
 Turn-by-turn navigation (GPS)
getCurrentPosition() Method - Return Data
The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and
accuracy properties are always returned.

Property Description
coords.latitude The latitude as a decimal number
coords.longitude The longitude as a decimal number
coords.accuracy The accuracy of position
coords.altitude The altitude in meters above the mean sea level
coords.altitude The altitude accuracy of position
Accuracy
The heading as degrees clockwise from North
coords.heading The speed in meters per second

coords.speed The date/time of the response

timestamp

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.
142- HTML5 Drag/Drop
HTML5 Drag and Drop
Drag and drop is a part of the HTML5 standard. Drag and drop is a very common feature.
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. 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
We need to take care of ondragover and ondrop events.

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

function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");

ev.target.appendChild(document.getElementById(data));
}
Drag Drop
To Drag:

 Make element dragable
 Handle ondragstart
Where to Drop:
 Handle ondragover
 Handle ondrop

143- HTML5 Local Storage
HTML local storage: replacement of and better than cookies.

What is HTML Local Storage?
With local 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.

 More secure
 Large amounts of data (5mb) can be stored locally.
 Information is never transferred to the server.
HTML Local Storage Objects
HTML local 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 tab is closed)
Before using local storage, check browser support for localStorage and sessionStorage:

if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.

} else {
// 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
localStorage.setItem("lastname", "Adeel");
// Retrieve
var str = localStorage.getItem("lastname");
Example:
// Store
localStorage.lastname = "Adeel";
// Retrieve

var str = localStorage.lastname;

// To Remove

localStorage.removeItem("lastname");

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

The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for
only one session.

144- HTML5 App Cache

With application cache it is easy to make an offline version of a web application, by creating a cache
manifest file.

What is Application Cache?

HTML5 introduces application cache, which means that a web application is cached, and
accessible without an internet connection. Application cache gives an application three
advantages:

 Offline browsing
 Speed
 Reduced server load

See the example:

<!DOCTYPE HTML>

<html manifest="demo.appcache">

<body>

The content of the document......

</body>

</html>

Cache Manifest Basics

To enable application cache, include the manifest attribute in the document's <html> tag:

<!DOCTYPE HTML>

<html manifest="demo.appcache">

...

</html>

Every page with the manifest attribute specified will be cached. If the manifest attribute is not
specified, the page will not be cached. The recommended file extension for manifest file is:
".appcache"

The Manifest File

The manifest file is a simple text file, which tells the browser what to cache (and what to never
cache).

The Manifest File

The manifest file has three sections:

 CACHE MANIFEST - Files listed under this header will be cached after they are
downloaded for the first time

 NETWORK - Files listed under this header require a connection to the server, and will
never be cached

 FALLBACK - Files listed under this header specifies fallback pages if a page is
inaccessible

CACHE MANIFEST

The first line, CACHE MANIFEST, is required:

 CACHE MANIFEST
 /theme.css
 /logo.gif
 /main.js

NETWORK

The NETWORK section below specifies that the file "login.asp" should never be cached, and will
not be available offline:

 NETWORK:
 login.asp

An asterisk can be used to indicate that all other resources/files require an internet connection:

NETWORK:

*

FALLBACK

The FALLBACK section below specifies that "offline.html" will be served in place of all files in
the /html/ catalog, in case an internet connection cannot be established:

FALLBACK:

/html/ /offline.html

Updating the Cache

Once an application is cached, it remains cached until one of the following happens:
 The user clears the browser's cache
 The manifest file is modified
 The application cache is programmatically updated

Notes on Application Cache
Be careful with what you cache. Once a file is cached, the browser will continue to show the
cached version, even if you change the file on the server. To ensure the browser updates the
cache, you need to change the manifest file.

145- HTML5 Web Workers
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. Web worker runs in the background.

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.

var i = 0;
function timedCount() {

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

var i = 0;
function timedCount() {

i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
postMessage() method - is used to post a message back to the HTML page.

Web Worker Object
Now that we have the web worker file, we need to call it from an HTML page. Let’s creates a
new web worker object and runs the code in "test.js"

if(typeof(w) == "undefined") {
w = new Worker("test.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
Terminating 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
variable:

w = undefined;

Web Workers and the DOM
Web workers do not have access to the following JavaScript objects:

 The window object
 The document object
 The parent object

146- HTML5 SSE

HTML5 Server-Sent Events
A server-sent event is when a web page automatically get updates from a server.

Server-Sent Events - One Way Messaging
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. See the example below:

var source = new EventSource “sse.php" ;

source.onmessage = function(event) {
res = document.getElementById("result")

res.innerHTML += event.data + "<br>";

};

 Create a new EventSource object, and specify the URL of the page sending the updates.
 Each time an update is received, the onmessage event occurs.

Check Server-Sent Events Support
It’s good to check for Server Support first.

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

// Yes! Server-sent events support!

// Some code.....

} else {
// Sorry! No server-sent events support..

}

Server-Side Code Example
To make SSE work, you need a server capable of sending data updates (like PHP or ASP). The
server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream".
Now you can start sending event streams.

The server-side event stream syntax is simple.

 Set the "Content-Type" header to "text/event-stream".
 Start sending event streams.

Code in PHP (sse.php):
<?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();
?>
<?php

 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

There are other events also available with EventSource object.

Events Description

onopen When a connection to the server is opened

onmessage When a message is received

onerror When an error occurs

==================---------==================

CSS3

CSS3 is the latest standard for CSS. It is divided into several separate documents called "modules". Each
module adds new capabilities or extends features defined in CSS 2, preserving backward compatibility.

CSS3 Modules
CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split into
smaller pieces). In addition, new modules are added. Some of the most important CSS3 modules are:

 Selectors
 Box Model
 Backgrounds and Borders
 Image Values and Replaced Content
 Text Effects
 2D/3D Transformations
 Animations
 Multiple Column Layout
 User Interface
Most of the new CSS3 properties are implemented in modern browsers.
149- CSS3 Round Corners

CSS3 border-radius Property
With CSS3, you can give any element "rounded corners", by using the border-radius property.
See below rounded corners for an element with a specified background color:

See below the CSS code for this element:
#rcorners {
border-radius: 25px;
background: brown;
padding: 20px;
width: 200px;
height: 150px;
}

CSS3 border-radius - Specify Each Corner
If you specify only one value for the border-radius property, this radius will be applied to all 4
corners. But you can specify each corner separately if you wish.

border-radius: 15px 50px 30px 5px
Four values: first value applies to top-left, second value applies to top-right, third value applies
to bottom-right, and fourth value applies to bottom-left corner.

border-radius: 15px 50px 30px
Three values: first value applies to top-left, second value applies to top-right and bottom-left, and
third value applies to bottom-right

border-radius: 15px 50px
Two values: first value applies to top-left and bottom-right corner, and the second value applies
to top-right and bottom-left corner
150- CSS3 Border Images
The CSS3 border-image property allows you to specify an image to be used instead of the normal border
around an element.
CSS3 border-image Property
The property has three parts:

 The image to use as the border
 Where to slice the image
 Define whether the middle sections should be repeated or stretched
Let’s use the following image:

The border-image property takes the image and slices it into nine sections, like a tic-tac-toe
board. It then places the corners at the corners, and the middle sections are repeated or stretched
as you specify.
For border-image to work, the element also needs the border property set!
Example

#borderimg {
border: 10px solid transparent;
padding: 15px;
border-image: url(border.png) 30 round;

}
border-image: url(border.png) 30 round;
Here, the middle sections of the image are repeated to create the border:

Example
#borderimg {

border: 10px solid transparent;
padding: 15px;
border-image: url(border.png) 30 stretch;
}
border-image: url(border.png) 30 stretch;
Here, the middle sections of the image are stretched to create the border:

CSS3 border-image - Different Slice Values
Different slice values completely changes the look of the border:
Example 1:

border-image: url(border.png) 50 round;
Example 2:

border-image: url(border.png) 20% round;
Example 3:

border-image: url(border.png) 30% round;
151a- CSS3 Backgrounds
CSS3 contains a few new background properties, which allow greater control of the background element.

 We can add multiple background images to one element.
 Some new CSS3 properties added too:

o background-size
o background-origin
o background-clip

CSS3 Multiple Backgrounds
CSS3 allows you to add multiple background images for an element, through the background-
image property.
The different background images are separated by commas, and the images are stacked on top of
each other, where the first image is closest to the viewer.
Background Size
The CSS3 background-size property allows you to specify the size of background images.
Before CSS3, the size of a background image was the actual size of the image. CSS3 allows us to
re-use background images in different contexts. The size can be specified in lengths, percentages,
or by using one of the two keywords: contain or cover.
The two other possible values for background-size are, contain and cover.
The contain keyword scales the background image to be as large as possible (but both its width
and its height must fit inside the content area).

background-size: contain;

The contain keyword scales the background image to be as large as possible (but both its width
and its height must fit inside the content area).

background-size: cover;

The cover keyword scales the background image so that the content area is completely covered
by the background image (both its width and height are equal to or exceed the content area). As
such, some parts of the background image may not be visible in the background positioning area.

Define Sizes of Multiple Background Images

The background-size property also accepts multiple values for background size (using a comma-
separated list), when working with multiple backgrounds.

Example

#example1 {

background:

url(img1.gif) left top no-repeat,

url(img2.gif) right bottom no-repeat,

url(img3.gif) left top repeat;

background-size: 50px, 130px, auto;

}

Full Size Background Image
Let’s make a background image that cover entire browser all the time. See this example:

html {

background: url(img.jpg) no-repeat center center fixed;

background-size: cover;

}

CSS3 background-origin Property
The CSS3 background-origin property specifies where the background image is positioned.

The property takes three different values:

 border-box - the background image starts from the upper left corner of the border
 padding-box - (default) the background image starts from the upper left corner of the

padding edge
 content-box - the background image starts from the upper left corner of the content

CSS3 background-clip Property
The CSS3 background-clip property specifies the painting area of the background.

The property takes three different values:

 border-box - (default) the background is painted to the outside edge of the border
 padding-box - the background is painted to the outside edge of the padding
 content-box - the background is painted within the content box

152- CSS3 Colors

CSS supports color names, hexadecimal and RGB colors. CSS3 also introduces:

 RGBA colors
 HSL colors
 HSLA colors
 opacity

RGBA Colors

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 (fully opaque).

HSL Colors

HSL stands for Hue, Saturation and Lightness. An HSL color value is specified with:

hsl(hue, saturation, lightness)

 Hue is a degree on the color wheel (from 0 to 360):
o 0 (or 360) is red
o 120 is green
o 240 is blue

 Saturation is a percentage value: 100% is the full color.
 Lightness is also a percentage; 0% is dark (black) and 100% is white.

HSLA Colors

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)

Here the alpha parameter defines the opacity. The alpha parameter is a number between 0.0 (fully
transparent) and 1.0 (fully opaque).

Opacity

The CSS3 opacity property sets the opacity for a specified RGB value. The opacity property
value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).

153a- CSS3 Gradients
CSS3 gradients let you display smooth transitions between two or more specified colors.

 Reduce download time and bandwidth usage.
 Looks good when zoomed

Gradient Types
 Linear Gradients (goes down/ up/ left/ right/ diagonally)
 Radial Gradients (defined by their center)

CSS3 Linear Gradients
To create a linear gradient you must define at least two color stops. Color stops are the colors you
want to render smooth transitions among. You can also set a starting point and a direction (or an
angle) along with the gradient effect. Here is syntax for linear gradient:

background: linear-gradient (direction, color-stop1, color-stop2, ...);
Using Angles
If you want more control over the direction of the gradient, you can define an angle, instead of the
predefined directions (to bottom, to top, to right, to left, to bottom right, etc.).

Syntax
background: linear-gradient(angle, color-stop1, color-stop2);
here is a detailed example:
#gradient {
background: -webkit-linear-gradient(180deg, red, blue); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(180deg, red, blue); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(180deg, red, blue); /* For Firefox 3.6 to 15 */
background: linear-gradient(180deg, red, blue);
}
The angle is specified as an angle between a horizontal line and the gradient line, going counter-
clockwise. In other words, 0deg creates a bottom to top gradient, while 90deg generates a left to
right gradient.
Using Multiple Color Stops
We can add multiple color stops to make multi color gradient.
#gradient {
background: -webkit-linear-gradient(red, green, blue); /* For Safari 5.1 to 6.0 */

background: -o-linear-gradient(red, green, blue); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(red, green, blue); /* For Firefox 3.6 to 15 */
background: linear-gradient(red, green, blue);
}
Using Transparency
CSS3 gradients also support transparency, which can be used to create fading effects.
#grad {
background: linear-gradient (to right, rgba(255,0,0,0), rgba(255,0,0,1));
}
Repeating a linear-gradient
The repeating-linear-gradient() function is used to repeat linear gradients.
#grad {
background: repeating-linear-gradient (red, yellow 10%, green 20%);
}
CSS3 Radial Gradients
A radial gradient is defined by its center. To create a radial gradient you must also define at least
two color stops. Check here an Example of Radial Gradient:
background: radial-gradient(shape size at position, start-color, ..., last-color);
Radial Gradient - Differently Spaced Color Stops:
#grad {
background: radial-gradient(red 5%, green 15%, blue 60%);
}
Set Shape
The shape parameter defines the shape. It can take the value circle or ellipse. The default value is
ellipse.
#grad {
background: radial-gradient(circle, red, yellow, green);
}
Size of Gradient

The size parameter defines the size of the gradient. It can take four values:
 closest-side
 farthest-side
 closest-corner
 farthest-corner

Repeating a radial-gradient
The repeating-radial-gradient() function is used to repeat radial gradients.

#grad {
background: repeating-radial-gradient(red, yellow 10%, green 15%);
}
154- CSS3 Shadow Effects
Shadow Effects
With CSS3 you can add shadow to text and to elements.
Using properties:
 text-shadow
 box-shadow
CSS3 Text Shadow
The CSS3 text-shadow property applies shadow to text. In its simplest use, you only specify the
horizontal and vertical shadow:
h1 {

text-shadow: 2px 2px;
}

Add a color to the shadow:
h1 {
text-shadow: 2px 2px red;
}

Add a blur effect to the shadow:
h1 {


Click to View FlipBook Version