HTML 5 and           web standardsBrief History of web standards   CanvasWhy HTML 5 and When?             Data StorageW3C ...
First Things FirstLet s Understand The       History
History of HTML:1999: HTML 4,01 -W3C decide that they would not continue to evolve HTML2000: XHTML 1- A XML version of HTM...
HTML 5 Why , When , What?“...extending the language to better support Webapplications [...] This puts HTML in directcompet...
Is HTML 5 ready for production yet?W3C don’t think so! HTML5 will reach the Proposed Recommendation Stage sometime in 2022...
So can we use it now or not?    There won’t be a single point in time at which we    can declare that the language [HTML5]...
But wait which of browsercurrently support the HTML            5?
W3C SpecificationWhere we are? What s done?
ECMA                                  ECMA                                  Script                                        ...
Re-LearningSyntax:• Attribute quotes “not really” required• UPPERCASE and lowercase HTML elements allowed (CaMeLcAse typin...
STARTING OUTBASIC HTML 5 LAYOUT
XHTML 1,0 Transitional :<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xht...
Syntax:But wait there is more, if we go to w3c and try to validate this:http://validator.w3.org/#validate_by_inputThen we ...
<HEADER>             <NAV> <SECTION>  <ARTICLE>   <Figure>                     <ASIDE>Img,video,audio    legend        <FO...
<body>                      <header> <header>                      <h1>Title</h1>  <hgroup>                    </header>  ...
<!DOCTYPE HTML>                        <header>                                      <html>                               ...
Article VS Aside VS Section VS Div• Section- is a thematic grouping of content, typically with a heading –pretty generic, ...
But what about IE 6-8?current and old browsers “support” these(although some need a little extra help)header, footer, … { ...
HTML 5 Redefined Element:<ol>-has a new reversed attribute (not implemented yet), also start attribute is valid<dl>- Not a...
HTML 5 Unsupported                                                              Element:             Used for defining an ...
Html 5New API Available
HTML 5 New Selectors API:Finding elements by class (DOM API)Finding elements by CSS syntax (Selectors API):
Custom data-* attributes:Define, store, and retrieve custom data on the DOM:Output:
WAI-ARIA Attributes:Web Accessibility Initiative’s Accessible Rich Internet Applications <ul id="tree1"                   ...
Manipulate Class in native way:<div id="main" class="rounded"></div>
Improved FormsMaking Common UI Needs Native
Rich Form Elements – without                 JavaScript<input   type=”date”><input   type=”time”><input   type=”month”><in...
Built-in Validation(with attributes                 ) <input   … required> <input   type=”tel”> <input   type=”email”> <in...
HTML 5 New Form Options:Placeholder-displays init text                           Enter Search Value..       Search        ...
Native <video> And Improved <audio>
New HTML5 <video> as native objectIndustry-standard MPEG-4/H.264 videoVideo can be composited with anything else on the pa...
Video as native object-what does it              means? ● “plays nice” with rest of the page ● keyboard accessibility buil...
A Big Debate about video formats MP4 / H.264 Ogg Theora                                                      WebM         ...
Providing HTML 5 Cross Browser                <video><video controls autoplay poster="…" width="…" height="…">  <source sr...
HTML 5 Nice Audio:        Industry-standard MP3 and AAC audio                     Fully scriptable via the DOM <audio id="...
HTML 5 Media Basic Controls: Autoplay- plays the video or audio automatically Controls - providing controls may be overwri...
Video and Audio Fallback:Good way to include fallback for all browsers               http://mediaelementjs.com
Html5 CanvasThe future of graphics on the             Web
What is Canvas?<canvas id="myCanvas" width="200" height="200">  Your browser doesn’t support Canvas, sorry.</canvas><scrip...
What is SVG(Scalable Vector                 Graphics)?Create and draw 2D vector graphics using XML    •Vector images are c...
Fallback/Helpful JS Libraries:Raphael (SVG) – Dmitry Baranovskiy   Processing JS (Canvas) – John Resig      http://www.rap...
When Canvas or SVGSVG->High Level                             Canvas->Low Level-Import/Export                             ...
Data StorageExpect the Unexpected
Finally Web Storage Here(Cookies             suck):
Web SQL Database:         http://hacks.mozilla.org/2010/06/comparing-indexeddb-and-webdatabase/IndexedDB:var idbRequest = ...
OfflineHow the WEB can be Offline?
Application Cache:cache.manifest:
Drag and DropThe Native API
Native Drag & Drop:<div draggable="true">This element be draggable</div>document.addEventListener(dragstart, function(even...
Desktop Drag-OutDrag files out onto the desktop: <a href="src/star.mp3" draggable="true" class="dragout"  data-downloadurl...
GeolocationWhere is me?
Geolocation:getCurrentPosition -is a one-shot method for grabbing the user’s current location.watchPosition -keeps an eye ...
Device Orientation:window.addEventListener(deviceorientation, function(event) {//detect significant change in orientation ...
Web SocketsTwo-Way Communication
Web Workers (Threads):A worker is a way of running a discrete block of JavaScript in a background process to the main brow...
What you can do inside a worker?• postMessage and listen for inbound messages via onmessage• close, to end the current wor...
Web Sockets:WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSHtechnology. Both the ...
Notification:if (window.webkitNotifications.checkPermission() == 0) {  // you can pass any url as a parameter  window.webk...
Html 5 Revolution
Html 5 Revolution
Html 5 Revolution
Html 5 Revolution
Html 5 Revolution
Html 5 Revolution
Html 5 Revolution
Upcoming SlideShare
Loading in …5
×

Html 5 Revolution

3,545 views

Published on

Describe innovation of html 5

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,545
On SlideShare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
Downloads
16
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Html 5 Revolution

  1. 1. HTML 5 and web standardsBrief History of web standards CanvasWhy HTML 5 and When? Data StorageW3C Specification OfflineHtml Structure Drag and DropForms GeolocationVideo and Audio Web Sockets
  2. 2. First Things FirstLet s Understand The History
  3. 3. History of HTML:1999: HTML 4,01 -W3C decide that they would not continue to evolve HTML2000: 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-standard2002: XHTML 2-W3C decide to make more logical ,better designed language and broke backwards compatibility,,,2002-2003: Opera proof of concept: Web Forms 1.02003: XForms – A Model-View-Container approach2004: WHATWG -Web Hypertext Application Technology Working Group2007: HTML 5
  4. 4. HTML 5 Why , When , What?“...extending the language to better support Webapplications [...] This puts HTML in directcompetition with other technologies[...] , inparticular Flash and Silverlight.” Changes in the markup New APIs are available • New document type • 2D drawing • New elements • Timed media playback • Allows more semantic web pages • Offline storage • Etc. (will be discussed later) More Semantic Media Tags Geolocation Canvas Input TypesForm Validation HTML tags Draggable Local Storage Cross-Domain Web Sockets Eventually, 3DForm Validation Messaging canvas
  5. 5. Is HTML 5 ready for production yet?W3C don’t think so! HTML5 will reach the Proposed Recommendation Stage sometime in 2022”. 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 Answer:The specification is still in draft so it is reasonable to assume that some aspects maypossibly change. Browsers therefore can’t be expected to get it right, or implement it inthe same way as each other, thus going against the main aim of HTML 5
  6. 6. So can we use it now or not? There won’t be a single point in time at which we can declare that the language [HTML5] is ready to use. Instead, we can start using parts of the specification as web browsers support those Features
  7. 7. But wait which of browsercurrently support the HTML 5?
  8. 8. W3C SpecificationWhere we are? What s done?
  9. 9. ECMA ECMA Script Recommendation 262 ECMAScript 262 Geolocation Geolocation API Filters Fonts SMIL Gradients and Patterns Styling SVG Scripting Painting, Filling, Color Transforms Text Paths Basic Shapes Recommendatio Document Structure DOM L3 Abstract Schemas Candidate DOM L3 Views and FormattingThe Map of HTML 5 Specs: DOM L3 XPath n DOM L3 Validation DOM L3 Load and Save DOM L3 Events DOM L3 Core DOM L2 HTML DOM L2 Traversal and Range DOM L2 Style DOM L2 Events DOM L2 Views Web Apps DOM L2 Core DOM L1 XmlHttpRequest L2 XmlHttpRequest Web Workers Web Storage Web Sockets API Web IDL Last Call Web SQL Database Web DOM Core W3C Uniform Messaging Policy Server-Sent Events Selectors API L2 Selectors API Progress Events Programmable HTTP Caching and Serving Index DB File API Element Traversal CORS CSS Animations CSS Transitions Working Draft CSS 3D Transformations CSS 2D Transformations CSS Image Values CSS Flexible Box Layout CSS Grid Positioning CSS Scoping CSS Basic User Interface CSS Color CSS Speech CSS Media Queries CSS Template Layout CSS CSS Multi-column Layout CSS Basic Box Model CSS Fonts CSS Backgrounds and Borders CSS Generated Content for Paged Media CSS Ruby Working Draft CSS Line Grid First Public CSS Writing Modes CSS Text CSS Cascading and Inheritance CSS Values and Units CSS Print Profile CSS Paged Media CSS Namespaces CSS Snapshot 2007 Text alternatives Polyglot Markup HTML HTML5 Diff from HTML4 HTML5 Markup HTML+RDFa Microdata Canvas 2D Context HTML5
  10. 10. Re-LearningSyntax:• 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,
  11. 11. STARTING OUTBASIC HTML 5 LAYOUT
  12. 12. 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>
  13. 13. Syntax:But wait there is more, if we go to w3c and try to validate this:http://validator.w3.org/#validate_by_inputThen we type the following HTML (below) and hit validate: <!DOCTYPE html> <title>Small HTML5</title> <p>HELLO WORLD </p>
  14. 14. <HEADER> <NAV> <SECTION> <ARTICLE> <Figure> <ASIDE>Img,video,audio legend <FOOTER>
  15. 15. <body> <header> <header> <h1>Title</h1> <hgroup> </header> <h1>Page title</h1> <section> <h2>Page subtitle</h2> Content... </hgroup> </section> </header> </article> </section> <nav> <ul> <aside> Navigation... Top links... </ul> </aside> </nav> <section> <figure> <article> <img src="..."/> <header> <figcaption>Chart 1.1</figcaption> <h1>Title</h1> </figure> </header> <section> <footer> Content... Copyright © </section> <time datetime="2010-11-08">2010</time>. </article> </footer> <article
  16. 16. <!DOCTYPE HTML> <header> <html> <body> <header> <nav> <h1>Title</h1> </header> <article> <nav> <a href=“home.html”>Home</a> <a href=“about.html”>About</a> <aside> </nav> <section> <article> <h1>Article title..</h1> <p>Text…..</p> </article> <section> <footer> <p>Section1</p> </section><header> Defines a header for a section or page <aside> <p>About us…<p> </aside><nav> Defines navigation links <footer> <p>All rights received</p><aside> Defines content aside from the page content </footer> </body><article> Defines an article </html><section> Defines a section<footer> Defines a footer for a section or page
  17. 17. 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.
  18. 18. But what about IE 6-8?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); http://code.google.com/p/html5shim/document.createElement(section);document.createElement(article); http://www.modernizr.com/document.createElement(aside);document.createElement(footer);http://html5doctor.com/how-to-get-html5-working-in-ie-and-firefox-2
  19. 19. 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) <p>The <i>Titanic</i> sails at dawn.</p> <p>The design needs a bit more <i lang=fr>ooh la la</i>.</p><em>- marks up emphasis of the kind that subtly changes the meaning of a sentence <p>You, sir, deserve a jolly good kick up the <i>gluteus<i>- represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose maximus</i>!</p><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
  20. 20. HTML 5 Unsupported Element: Used for defining an acronym. For example, NHL. Theres<acronym> not a clear cut alternative, consider using <section> or <mark> <frameset> Used to define a frame set. <applet> Used for defining an embedded applet. An alternative you could consider using is the new <embed> tag. <noframes> Used to display text for browsers that didnt support frames. I dont think an alternative is required. Used for defining a base font color, size, or font family for Used to put a strikethrough text. As an alternative,<basefont> an entire document. You should already be doing this using CSS on the body selector, <s> you can use the <del> tag. Used for making text bigger. An easy alternative to this Used to put a strikethrough text. As an alternative, <big> would be to use some CSS to create a class called .big. Then <strike> you can use the <del> tag. wrap any text you want to be big in a tag with Used to define teletype text. As an alternative, use <center> Used to center text or elements. <tt> CSS to style the particular text with a class. Used to add an underline to text. As an alternative, <dir> Used to define a directory list <u> use the CSS text-decoration property. Used to define pre-formatted text. Instead, you <frame> Used to define a frame. Side Note: YES! NO MORE FRAMES! Alternative? Study layout design and hierarchy. <xmp> should use the <pre> tag, Full List: http://www.html-5.com/changes/deprecated/
  21. 21. Html 5New API Available
  22. 22. HTML 5 New Selectors API:Finding elements by class (DOM API)Finding elements by CSS syntax (Selectors API):
  23. 23. Custom data-* attributes:Define, store, and retrieve custom data on the DOM:Output:
  24. 24. WAI-ARIA Attributes:Web Accessibility Initiative’s Accessible Rich Internet Applications <ul id="tree1" • application role="tree" • article tabindex="0" • banner aria-labelledby="label_1"> <li role="treeitem" tabindex="-1" aria-expanded="true">Fruits</li> • complementary <li role="group"> • contentinfo <ul> • document <li role="treeitem" tabindex="-1">Oranges</li> • form <li role="treeitem" tabindex="-1">Pineapples</li> • heading ... </ul> • main </li> • navigation </ul> • search
  25. 25. Manipulate Class in native way:<div id="main" class="rounded"></div>
  26. 26. Improved FormsMaking Common UI Needs Native
  27. 27. 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>
  28. 28. 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
  29. 29. HTML 5 New Form Options:Placeholder-displays init text Enter Search Value.. Search <input id="status" name="status" type="text" autofocus>Autofocus-focus form on element <input id="pass" name="pass" type="password" required>Required-prevent form submissions ifrequired fields haven’t been filled out <form action="/selfdestruct" autocomplete="off"> <input type="text" name="hworld“ list="planets">Autocomplete-automatically filling in forms <datalist id="planets"> <option value="Mercury">Datalist-allows you to crossbreed a regular <option value="Venus">input element with a select element. </datalist>
  30. 30. Native <video> And Improved <audio>
  31. 31. New HTML5 <video> as native objectIndustry-standard MPEG-4/H.264 videoVideo can be composited with anything else on the page • HTML content, images, SVG graphics • Hardware accelerated, GPU-based decoding<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>
  32. 32. 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/
  33. 33. A Big Debate about video formats MP4 / H.264 Ogg Theora WebM “free and open”, no open and royalty-free, web ubiquitous, patent encumbered, licensing/royalties not many tools optimized support by software and licensing/royalties for it, not web optimised hardware vendors
  34. 34. 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&amp;image=__POSTER__.JPG&amp;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 browsers http://camendesign.com/code/video_for_everybody
  35. 35. 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>Simple JS API: Simple JS API: <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>
  36. 36. 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 looppreload=‚auto‛ preload=metadata></video>
  37. 37. Video and Audio Fallback:Good way to include fallback for all browsers http://mediaelementjs.com
  38. 38. Html5 CanvasThe future of graphics on the Web
  39. 39. What is Canvas?<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>
  40. 40. 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/
  41. 41. Fallback/Helpful JS Libraries:Raphael (SVG) – Dmitry Baranovskiy Processing JS (Canvas) – John Resig http://www.raphaeljs.com/ http://www.processingjs.org/
  42. 42. When Canvas or SVGSVG->High Level Canvas->Low Level-Import/Export -No mouse Interaction-Easy UI VS -High Animation-Iterative -JS Centric-Medium Animation -More Bookkeeping-Tree of Objects -Pixels-Layer based-Separate files -Html Element
  43. 43. Data StorageExpect the Unexpected
  44. 44. Finally Web Storage Here(Cookies suck):
  45. 45. Web SQL Database: http://hacks.mozilla.org/2010/06/comparing-indexeddb-and-webdatabase/IndexedDB:var idbRequest = window.indexedDB.open(Database Name); Chrome -Supported in version 3.0 and greateridbRequest.onsuccess = function(event) { Firefox -Supported in version 3.0 and greater var db = event.result; var transaction = db.transaction([], IDBTransaction.READ_ONLY); IE -Supported in version 9.0 and greater var curRequest = transaction.objectStore(ObjectStore Name).openCursor(); Opera -Supported in version 10.5 and greater curRequest.onsuccess = ...;}; Safari -Supported in version 4.0 and greater
  46. 46. OfflineHow the WEB can be Offline?
  47. 47. Application Cache:cache.manifest:
  48. 48. Drag and DropThe Native API
  49. 49. Native Drag & Drop:<div draggable="true">This element be draggable</div>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);
  50. 50. Desktop Drag-OutDrag files out onto the desktop: <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); }
  51. 51. GeolocationWhere is me?
  52. 52. Geolocation: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 if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var coords = position.coords; }, errorHandler, { enableHighAccuracy: true, //use GPS for help timeout: 2000, //wait before error maximumAge: 0 //time of use cached position }); }
  53. 53. 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;});
  54. 54. Web SocketsTwo-Way Communication
  55. 55. Web Workers (Threads):A worker is a way of running a discrete block of JavaScript in a background process to the main browser.main.js: 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); };task.js: 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”); } };
  56. 56. 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
  57. 57. Web Sockets:WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSHtechnology. 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 reducingbandwidthvar 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); } http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/
  58. 58. 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();}

×