Brief History of web standards
Why HTML 5 and When?
W3C Specification
Html Structure
Forms
Video and Audio
HTML 5 andweb
standardsCanvas
Data Storage
Offline
Drag and Drop
Geolocation
Web Sockets
First Things First Let’s Understand The
History
1999: HTML 4,01 -W3C decide that they would not continue to evolve HTML
2000: XHTML 1- A XML version of HTML requiring XML syntax rules like quoting attributes,
2001: XHTML 1,1-Transitional,and Strict and Frameset become a valid professional-standard
2002: XHTML 2-W3C decide to make more logical ,better designed language and broke backwards compatibility,,,
2002-2003: Opera proof of concept: Web Forms 1.0
2003: XForms – A Model-View-Container approach
2004: WHATWG -Web Hypertext Application Technology Working Group
2007: HTML 5
History of HTML:
HTML 5 Why , When , What?“...extending the language to better support Web applications [...] This puts HTML in direct competition with other technologies[...] , in particular Flash and Silverlight.”
Eventually, 3D canvas
Web Sockets
More Semantic HTML tags
Media Tags Geolocation Canvas Input TypesForm Validation
Cross-Domain Messaging
Local StorageDraggableForm Validation
Changes in the markup• New document type• New elements• Allows more semantic web pages
New APIs are available• 2D drawing• Timed media playback• Offline storage• Etc. (will be discussed later)
HTML5 will reach the Proposed Recommendation Stage sometime in 2022”.
Is HTML 5 ready for production yet? W3C don’t think so!
The problem we’re facing right now is there is already a lot of excitement for HTML 5, but it’s a little too early to deploy it because we’re running into interoperability issues”
The specification is still in draft so it is reasonable to assume that some aspects may possibly change. Browsers therefore can’t be expected to get it right, or implement it in the same way as each other, thus going against the main aim of HTML 5
The Answer:
There won’t be a single point in time at which wecan declare that the language [HTML5] is ready touse. Instead, we can start using parts of thespecification as web browsers support thoseFeatures
So can we use it now or not?
But wait which of browser currently
support the HTML 5?
W3C Specification Where we are? What’s
done?
W3C
HTML
HTM
L5Canvas 2D
ContextM
icrodataH
TML+RD
FaH
TML5 M
arkupH
TML5 D
iff from H
TML4
Polyglot Markup
Text alternatives
CSS
CSS Snapshot 2007CSS N
amespaces
CSS Paged Media
CSS Print ProfileCSS Values and U
nitsCSS Cascading and Inheritance
CSS TextCSS W
riting Modes
CSS Line Grid
CSS RubyCSS G
enerated Content for Paged Media
CSS Backgrounds and BordersCSS Fonts
CSS Basic Box Model
CSS Multi-colum
n LayoutCSS Tem
plate LayoutCSS M
edia Queries
CSS SpeechCSS Color
CSS Basic User Interface
CSS ScopingCSS G
rid PositioningCSS Flexible Box Layout
CSS Image Values
CSS 2D Transform
ationsCSS 3D
Transformations
CSS TransitionsCSS Anim
ations
Web Apps
CORS
Element TraversalFile API
Index DB
Programm
able HTTP Caching and Serving
Progress EventsSelectors API
Selectors API L2Server-Sent Events
Uniform
Messaging Policy
Web D
OM
CoreW
eb SQL D
atabaseW
eb IDL
Web Sockets APIW
eb StorageW
eb Workers
XmlH
ttpRequest
XmlH
ttpRequest L2
DO
M L1
DO
M L2 Core
DO
M L2 View
sD
OM
L2 EventsD
OM
L2 StyleD
OM
L2 Traversal and RangeD
OM
L2 HTM
LD
OM
L3 CoreD
OM
L3 EventsD
OM
L3 Load and SaveD
OM
L3 ValidationD
OM
L3 XPathD
OM
L3 Views and Form
atting
DO
M L3 Abstract Schem
asSVG
Docum
ent StructureBasic Shapes
PathsText
Transforms
Painting, Filling, ColorScriptingStyling
Gradients and Patt
ernsSM
ILFontsFilters
Geolo
catio
nG
eolocation API
ECMA
ECMA Script
262
ECMAScript 262
First Public Working Draft Working Draft
Candidate Recommendatio
nRecommendationLast Call
The Map of HTML 5 Specs:
• Attribute quotes “not really” required
• UPPERCASE and lowercase HTML elements allowed (CaMeLcAse typing)
• No more need to do self-closing tags like <img/> or <BR/>
• Also, no more minimization, So, this is okay <dl compact>
• Basically, everything that was bad from HTML 4 in HTML 5 good again,
Re-Learning Syntax:
STARTING OUT BASIC HTML 5
LAYOUT
XHTML 1,0 Transitional :<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Sample Document</title> <link href="Styles/Site.css" rel="stylesheet" type="text/css" /> <script src="Scripts/jquery.js" type="text/javascript"></script></head>
HTML 5:<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>Sample Document</title> <link href="Styles/Site.css" rel="stylesheet"/> <script src="Scripts/jquery.js"></script>
But wait there is more, if we go to w3c and try to validate this:http://validator.w3.org/#validate_by_input
Then we type the following HTML (below) and hit validate:<!DOCTYPE html><title>Small HTML5</title><p>HELLO WORLD </p>
Syntax:
<body> <header> <hgroup> <h1>Demo page</h1> <h2>Semantic sample demo page</h2> </hgroup> </header>
<nav> <ul> Some nice looking navigation </ul> </nav>
<section> <article> <header> <h1>First Paragraph</h1> </header> <section> Lorem ipsum … </section> </article>
<aside> Some links and useful side notes </aside>
<footer> Timmy Kokke - Copyright © 2010. </footer></body>
<HEADER>
<NAV>
<ASIDE>
<FOOTER>
<ARTICLE>
<SECTION>
<Figure>
Img,video,audio
legend
<header> <h1>Title</h1> </header> <section> Content... </section> </article> </section>
<aside> Top links... </aside>
<figure> <img src="..."/> <figcaption>Chart 1.1</figcaption> </figure>
<footer> Copyright © <time datetime="2010-11-08">2010</time>. </footer>
<body> <header> <hgroup> <h1>Page title</h1> <h2>Page subtitle</h2> </hgroup> </header>
<nav> <ul> Navigation... </ul> </nav> <section> <article> <header> <h1>Title</h1> </header> <section> Content... </section> </article> <article
<header> Defines a header for a section or page
<nav> Defines navigation links
<aside> Defines content aside from the page content
<article> Defines an article
<section> Defines a section
<footer> Defines a footer for a section or page
<header>
<nav>
<article>
<footer>
<aside><section>
<!DOCTYPE HTML><html><body><header> <h1>Title</h1></header><nav> <a href=“home.html”>Home</a> <a href=“about.html”>About</a></nav><article> <h1>Article title..</h1> <p>Text…..</p></article><section> <p>Section1</p></section><aside> <p>About us…<p></aside><footer> <p>All rights received</p></footer></body></html>
Article VS Aside VS Section VS Div
• Section- is a thematic grouping of content, typically with a heading –pretty generic, it can contain articles as well and appear as requested.
• Article- is a discrete piece of content that could be syndicated –a blog post, a news item, a comment, a widget.
• Aside- is content that is tangentially related to its parent element. Or ,if a sibling to the main content, it can be used to make sidebars of navigations, recent comments, colophons, author bios etc.
• Div –has no semantic unless group stuff for styling.
current and old browsers “support” these(although some need a little extra help)header, footer, … { display: block; }
Internet Explorer needs extra training wheelsdocument.createElement('header');document.createElement('nav');document.createElement('section');document.createElement('article');document.createElement('aside');document.createElement('footer');http://html5doctor.com/how-to-get-html5-working-in-ie-and-firefox-2
But what about IE 6-8?
http://code.google.com/p/html5shim/
http://www.modernizr.com/
HTML 5 Redefined Element:
<ol>-has a new reversed attribute (not implemented yet), also start attribute is valid
<dl>- Not a Term and Definition anymore it’s a groups of name-value data
<cite>- been used to mark up the name of a speaker of citation ,no it’s specifies a citation only
<address>- been used as generic element for postal addresses, now it’s more global:
is for contact details of the author of the current <article> or document (more then one times)
<em>- marks up emphasis of the kind that subtly changes the meaning of a sentence
<i>- represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose
<strong>- represents strong importance for its contents
<b>- represents a key words or spans of text whose typical typographic presentation is boldened
<hr>- is now media-independent and indicates “aparagraph-level thematic break.”
<small>- not just small text it’s a “small print” licensing requirements.” or copyrights
<p>The <i>Titanic</i> sails at dawn.</p><p>The design needs a bit more <i lang=fr>ooh la la</i>.</p><p>You, sir, deserve a jolly good kick up the <i>gluteusmaximus</i>!</p>
HTML 5 Unsupported Element:
Used for defining an embedded applet. An alternative you could consider using is the new <embed> tag.
Used for defining a base font color, size, or font family for an entire document. You should already be doing this using CSS on the body selector,
Used for making text bigger. An easy alternative to this would be to use some CSS to create a class called .big. Then wrap any text you want to be big in a tag with
Used to center text or elements.
Used to define a directory list
Used to define a frame. Side Note: YES! NO MORE FRAMES! Alternative? Study layout design and hierarchy.
Used to define a frame set.
Used to display text for browsers that didn't support frames. I don't think an alternative is required.<noframes>Used to put a strikethrough text. As an alternative, you can use the <del> tag.<s>Used to put a strikethrough text. As an alternative, you can use the <del> tag.<strike>Used to define teletype text. As an alternative, use CSS to style the particular text with a class.<tt>Used to add an underline to text. As an alternative, use the CSS text-decoration property.<u>Used to define pre-formatted text. Instead, you should use the <pre> tag,<xmp>
Used for defining an acronym. For example, NHL. There's not a clear cut alternative, consider using <section> or <mark>
<acronym>
<applet>
<basefont>
<big>
<center>
<dir>
<frame>
<frameset>
Full List: http://www.html-5.com/changes/deprecated/
Html 5 New API Available
HTML 5 New Selectors API:
var el = document.getElementById('section1');el.focus();var els = document.getElementsByTagName('div');els[0].focus();var els = document.getElementsByClassName('section');els[0].focus();
Finding elements by CSS syntax (Selectors API):var els = document.querySelectorAll("ul li:nth-child(odd)");var tds = document.querySelectorAll("table.test > tr > td");var el = document.querySelector("table.test > tr > td"); // el == tds[0]
Return the first element in the page which matches the specifiedm selector rules(s)
Returns all elements which match thespecified rule or rules
Finding elements by class (DOM API)
Custom data-* attributes:
<div id="out" data-id="good" data-name="joe" data-screen-name="user1"></div>
Define, store, and retrieve custom data on the DOM:
// Add new data attributes via JS.var el = document.querySelector('#out');el.setAttribute('data-foo', 'bar');var html = [];for (var key in el.dataset) { html.push(key, ': ', el.dataset[key], '<br>');}el.innerHTML = html.join('');
Output:id: goodname: joescreenName: user1foo: bar
WAI-ARIA Attributes:
<ul id="tree1" role="tree" tabindex="0" aria-labelledby="label_1"> <li role="treeitem" tabindex="-1" aria-expanded="true">Fruits</li> <li role="group"> <ul> <li role="treeitem" tabindex="-1">Oranges</li> <li role="treeitem" tabindex="-1">Pineapples</li> ... </ul> </li></ul>
Web Accessibility Initiative’s Accessible Rich Internet Applications
• application
• article
• banner
• complementary
• contentinfo
• document
• form
• heading
• main
• navigation
• search
Manipulate Class in native way:
<div id="main" class="shadow rounded"></div>
var el = document.querySelector('#main').classList;el.add('highlight');el.remove('shadow');el.toggle('highlight');
console.log(el.contains('highlight')); // falseconsole.log(el.contains('shadow')); // falseconsole.log(el.classList.toString() == el.className); // true
Output:<div id="main" class="rounded"></div>
THE BEATY OF THE WEBHTML 5 DEMO
Improved Forms Making Common UI Needs
Native
Rich Form Elements – without JavaScript
<input type=”date”><input type=”time”><input type=”month”><input type=”week”><input type=”datetime” … ><input type=”range”><input type=”number”><input type=”file” multiple><input … autofocus><input … autocomplete>
Built-in Validation(with attributes )
<input … required><input type=”tel”><input type=”email”><input type=”url”><input … pattern="[a-z]{3}[0-9]{3}">
Demos:http://people.opera.com/patrickl/experiments/forms/newtypes.htmlhttp://people.opera.com/patrickl/experiments/forms/date-time.htmlhttp://people.opera.com/patrickl/experiments/forms/validation.htmlhttp://people.opera.com/patrickl/experiments/forms/progress.html
HTML 5 New Form Options:
Placeholder-displays init text
Autofocus-focus form on element
Required-prevent form submissions if required fields haven’t been filled out
Autocomplete-automatically filling in forms
Datalist-allows you to crossbreed a regular input element with a select element.
Enter Search Value.. Search<input id="status" name="status" type="text" autofocus>
<form action="/selfdestruct" autocomplete="off">
<input type="text" name="hworld“ list="planets"> <datalist id="planets">
<option value="Mercury"> <option value="Venus">
</datalist>
<input id="pass" name="pass" type="password" required>
THE BEATY OF THE WEBHTML 5 DEMO
Native <video> And Improved <audio>
New HTML5 <video> as native object
<video src="video.mp4" id="videoTag" width="640px" height="360px">
<video src="video.webm" controls autoplay poster="poster.jpg" width="320“ height="240"> <a href="video.webm">Download movie</a>
</video></video>
Industry-standard MPEG-4/H.264 video
Video can be composited with anything else on the page• HTML content, images, SVG graphics• Hardware accelerated, GPU-based decoding
Video as native object-what does it means?
● “ ” plays nice with rest of the page● keyboard accessibility built-in● API for controls: v = document.getElementById('myVideo'); v.play();v.pause(); Demos:http://people.opera.com/patrickl/experiments/webm/basic-controls/http://people.opera.com/patrickl/experiments/webm/fancy-controls/http://people.opera.com/patrickl/experiments/webm/fancy-swap/
A Big Debate about video formats
ubiquitous, patent encumbered, licensing/royalties
“free and open”, no licensing/royalties not many tools
for it, not web optimised
open and royalty-free, web optimized support by software and
hardware vendors
MP4 / H.264 Ogg Theora WebM
Providing HTML 5 Cross Browser <video>
<video controls autoplay poster="…" width="…" height="…"> <source src="movie.webm" type="video/webm" /> <source src="movie.ogv" type="video/ogg" /> <source src="movie.mp4" type="video/mp4" /> <!-- fallback content --> <object width="640" height="360" type="application/x-shockwave-flash" data="__FLASH__.SWF"> <param name="movie" value="__FLASH__.SWF" /> <param name="flashvars“ value="controlbar=over&image=__POSTER__.JPG&file=__VIDEO__.MP4" /> <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__" title="No video playback capabilities, please download the video below" />
</object> </video>
still include fallback for old browsershttp://camendesign.com/code/video_for_everybody
HTML 5 Nice Audio:
Industry-standard MP3 and AAC audio Fully scriptable via the DOM
<audio id="audioTag" autoplay controls preload=“none”> <source src="witchitalineman.ogg" type="audio/ogg"> <source src="witchitalineman.mp3" type="audio/mpeg"> <!–- Flash Fallback--> <object type="application/x-shockwave-flash" data="player.swf?soundFile=witchitalineman.mp3"> <param name="movie"value="player.swf?soundFile=witchitalineman.mp3"> </object>
</audio>
<div> <button onclick="document.getElementById('player').play()"> Play </button> <button onclick="document.getElementById('player').pause()"> Pause </button> <button onclick="document.getElementById('player').volume+= 0.1"> Volume Up </button> <button onclick="document.getElementById('player').volume-= 0.1"> Volume Down</button>
</div>
Simple JS API:Simple JS API:
HTML 5 Media Basic Controls:
Autoplay- plays the video or audio automatically
Controls - providing controls may be overwritten
Poster - points to an image that the browser will use while the video is downloading
height, width - size in pixels of the video
Loop- loops the media playback
Preload- suggest to buffer the media, before control is activated
<video src="video.mp4" id="videoTag“ poster=“post.jpg” width="640px" height="360px“ autoplay=“false” controls loop preload=“auto” preload=metadata></video>
Video and Audio Fallback:
Good way to include fallback for all browsers
http://mediaelementjs.com
Html5 Canvas The future of graphics on
the Web
What is Canvas?
A block element that allows developers to draw 2d graphics using JavaScript
Methods for drawing include: paths, boxes, circles, text and rasterized images
...also it’s supporting video and audio
<canvas id="myCanvas" width="200" height="200"> Your browser doesn’t support Canvas, sorry.</canvas>
<script type="text/javascript"> var ctx = document.querySelector(‘canvas’).getContext(‘2d’); ctx.fillStyle = "rgb(255,0,0)"; ctx.fillRect(30, 30, 50, 50); ctx.strokeStyle = ‘rgb(0, 0, 0)’; ctx.lineWidth = 5; ctx.strokeRect(9, 19, 52, 52); // draws an outline</script>
What is SVG(Scalable Vector Graphics)?
Create and draw 2D vector graphics using XML• Vector images are composed of shapes instead of pixels• Based on SVG 1.1• Rendered optimally on all sizes of devices
<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg"> <rect fill="red" x="20" y="20" width="100" height="75" /> <rect fill="blue" x="50" y="50" width="100" height="75" /></svg>
For more info visit: http://www.svgbasics.com/
Fallback/Helpful JS Libraries:
Raphael (SVG) – Dmitry Baranovskiyhttp://www.raphaeljs.com/
Processing JS (Canvas) – John Resighttp://www.processingjs.org/
THE BEATY OF THE WEBHTML 5 DEMO
When Canvas or SVG
SVG->High Level
-Import/Export
-Easy UI
-Iterative
-Medium Animation
-Tree of Objects
-Layer based
-Separate files
Canvas->Low Level
-No mouse Interaction
-High Animation
-JS Centric
-More Bookkeeping
-Pixels
-Html Element
VS
Data Storage Expect the Unexpected
Finally Web Storage Here(Cookies suck):
// use localStorage for persistent storage// use sessionStorage for per tab storagetextarea.addEventListener('keyup', function () { window.localStorage.setItem('value', area.value); window.localStorage.setItem('timestamp', (new Date()).getTime());}, false);textarea.value = window.localStorage.getItem('value');
<textarea id="ta" placeholder="Type your text here..."></textarea>
THE BEATY OF THE WEBHTML 5 DEMO
Web SQL Database:
if (window.openDatabase) {//always do a HTML 5 feature Check var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); // open or create a db db.transaction(function(tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS tweets(id, date, tweet)’, [], function () {
// now go and load the table up with tweets }); }); }
var idbRequest = window.indexedDB.open('Database Name');idbRequest.onsuccess = function(event) { var db = event.result; var transaction = db.transaction([], IDBTransaction.READ_ONLY); var curRequest = transaction.objectStore('ObjectStore Name').openCursor(); curRequest.onsuccess = ...;};
Chrome -Supported in version 3.0 and greater
Firefox -Supported in version 3.0 and greater
IE -Supported in version 9.0 and greater
Opera -Supported in version 10.5 and greater
Safari -Supported in version 4.0 and greater
IndexedDB:
http://hacks.mozilla.org/2010/06/comparing-indexeddb-and-webdatabase/
THE BEATY OF THE WEBHTML 5 DEMO
OfflineHow the WEB can be Offline?
Application Cache:
CACHE MANIFEST
# version 1
CACHE:/html5/src/refresh.png/html5/src/logic.js/html5/src/style.css/html5/src/background.png
<html manifest="cache.manifest">window.applicationCache.addEventListener('checking', updateCacheStatus, false);
cache.manifest:
THE BEATY OF THE WEBHTML 5 DEMO
Drag and DropThe Native API
Native Drag & Drop:
document.addEventListener('dragstart', function(event) { event.dataTransfer.setData('text', 'Customized text'); event.dataTransfer.effectAllowed = 'copy';}, false);
Drag files in from the desktop:document.querySelector('#dropzone').addEventListener('drop', function(e) { var reader = new FileReader(); reader.onload = function(evt) { document.querySelector('img').src = evt.target.result; }; reader.readAsDataURL(evt.dataTransfer.files[0]);}, false);
<div draggable="true">This element be draggable</div>
Desktop Drag-Out
<a href="src/star.mp3" draggable="true" class="dragout" data-downloadurl="MIMETYPE:FILENAME:ABSOLUTE_URI_TO_FILE">download</a>
var files = document.querySelectorAll('.dragout');for (var i = 0, file; file = files[i]; ++i) { file.addEventListener('dragstart', function(e) { e.dataTransfer.setData('DownloadURL', this.dataset.downloadurl); }, false);}
Drag files out onto the desktop:
Geolocation Where is me?
Geolocation:
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var coords = position.coords; }, errorHandler, {
enableHighAccuracy: true, //use GPS for helptimeout: 2000, //wait before errormaximumAge: 0 //time of use cached position
});}
getCurrentPosition -is a one-shot method for grabbing the user’s current location.
watchPosition -keeps an eye on their position and keeps polling at regular intervals to see if their location has changed.
clearWatch- clears particular watch
Device Orientation:
window.addEventListener('deviceorientation', function(event) {//detect significant change in orientation occurs var a = event.alpha; var b = event.beta; var g = event.gamma;});
Web SocketsTwo-Way Communication
Web Workers (Threads):
onmessage = function (event) { if (event.data == “hello worker!”) { postMessage(“hello there, right back at you”); } else { postMessage(“Can’t you see I’m busy, leave me alone”); }};
if (typeof Worker != “undefined”) {//always perform a feature detection var worker = new Worker('task.js'); worker.postMessage(‘hello worker!’); worker.onmessage = function (event) { alert(‘The worker just sent me this: ‘ + event.data); };}
main.js:
task.js:
A worker is a way of running a discrete block of JavaScript in a background process to the main browser.
What you can do inside a worker?
• postMessage and listen for inbound messages via onmessage
• close, to end the current worker
• Set event listeners
• XMLHttpRequest, for Ajax requests
• Timers, such as setTimeout, setInterval, and their clearing counterparts
• All the core JavaScript functions: eval, isNaN, escape, etc.
• Location object, the href of the worker script
• Web Sockets (which we’ll discuss in the final section of this chapter)
• Web SQL Databases
• Web Workers
• importScripts
Web Sockets:
var socket = new WebSocket("ws://localhost:8000/socket/server/startDaemon.php");socket.onopen = function(event) { socket.send('Hello, WebSocket');};socket.onmessage = function(event) { alert(event.data); }socket.onclose = function(event) { alert('closed'); }
WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSH technology. Both the server and client can send data at any time, or even at the same time. Only the data itself is sent, without the overhead of HTTP headers, dramatically reducing bandwidth
http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/
Notification:
if (window.webkitNotifications.checkPermission() == 0) { // you can pass any url as a parameter window.webkitNotifications.createNotification(tweet.picture, tweet.title, tweet.text).show();} else { window.webkitNotifications.requestPermission();}