0
HTML5 APIs -Where No Man Has  Gone Before!
classList
var elm = document.getElementById("classlist-demo");elm.classList.add("boxy");elm.classList.add("pretty");elm.classList.re...
Web Storage
sessionStorage.setItem("FU", "Sarah Palin");console.log(sessionStorage.getItem("FU"));
localStorage.setItem("Job", "Politician");
var sarahPalin = {    "contest" : "Miss Alaska pageant",    "Talent" : "Flute playing"};localStorage.setItem("sarah", JSON...
Web SQL   IndexedDB
IndexedDB
// IndexedDBvar indexedDB = window.indexedDB || window.webkitIndexedDB ||window.mozIndexedDB || window.OIndexedDB || windo...
createObjectStore = function (dataBase) {    // Create an objectStore    dataBase.createObjectStore("elephants");}// Curre...
request.onsuccess = function (event) {    // Create XHR    var xhr = new XMLHttpRequest(),        blob;    xhr.open("GET",...
putElephantInDb = function (blob) {    // Open a transaction to the database    var transaction = db.transaction(["elephan...
Offline Web Applications
if (window.addEventListener) {    /*        Works well in Firefox and Opera with the        Work Offline option in the Fil...
// Poll the navigator.onLine propertysetInterval(function () {    console.log(navigator.onLine);}, 1000);
<!DOCTYPE html><html manifest="offline.appcache"><head>...
CACHE MANIFEST# VERSION 10CACHE:offline.htmlbase.cssFALLBACK:online.css offline.cssNETWORK:/live-updates
History API
window.history.pushState(state, title, url);
var url = "http://robertnyman.com",title = "My blog",state = {    address : url};window.history.pushState(state, title, ur...
Web Sockets
LiveConnect    Forever Frame      HTTP Long-Polling and XHR Streaming    What came before WebSockets?      AJAX           ...
var ws = new WebSocket("ws://robertnyman.com/wsmagic");// Send dataws.send("Some data");// Close the connectionws.close();
var ws = new WebSocket("ws://robertnyman.com/wsmagic");// When connection is openedws.onopen = function () {    console.lo...
web-socket-js Socket.IO
File API
<!--       The multiple attribute allows for       uploading of multiple files--><input id="files-upload" type="file" mult...
var filesUpload = document.getElementById("files-upload");filesUpload.onchange = function () {    // Access to data about ...
for (var i=0, l=files.length, file, img; i<l; i++) {    file = files[i];    if (typeof FileReader !== "undefined") {      ...
// For Firefox, Google Chrome and Safarivar xhr = new XMLHttpRequest();xhr.open("post", "upload/upload.php", true);xhr.onr...
Drag and Drop
...I am forced to conclude thatthe HTML5 drag and dropmodule is not just a disaster, it’sa fucking disaster.              ...
<div id="can-be-dragged" draggable></div>
<p id="drop-area">     Drag and drop files here</p>
var someImg = document.getElementById("some-image"),    dropArea = document.getElementById("drop-area");someImg.ondragstar...
someImg.ondragstart = function (evt) {    var event = evt || window.event;    event.dataTransfer.setDragImage(dragIcon, -1...
Web Workers
var worker = new Worker("worker.js");
// Main page code    var worker = new Worker("worker.js");    // postMessage    worker.postMessage(5);    // Receive messa...
// Web Worker codeonmessage = function (evt) {    for (var i=evt.data, il=1000001; i<il; i++) {        postMessage(i);    ...
Fullscreen
<button id="view-fullscreen">Fullscreen</button><script type="text/javascript">(function () {    var viewFullScreen = docu...
mozRequestFullScreenWithKeys?
html:-moz-full-screen {    background: red;}html:-webkit-full-screen {    background: red;}
Camera
<input type="file" id="take-picture" accept="image/*">
takePicture.onchange = function (event) {    // Get a reference to the taken picture or chosen file    var files = event.t...
WebRTC
var liveVideo = document.querySelector("#live-video");navigator.getUserMedia(    {video: true},    function (stream) {    ...
Pointer Lock API
var docElm = document.documentElement;// Requesting Pointer LockdocElm.requestPointerLock = elem.requestPointerLock ||    ...
document.addEventListener("mousemove", function(e) {    var movementX = e.movementX       ||                    e.mozMovem...
Battery
// Get battery level in percentagevar batteryLevel = battery.level * 100 + "%";// Get whether device is charging or notvar...
battery.addEventLister("levelchange", function () {    // Devices battery level changed}, false);battery.addEventListener(...
Try new things
"So we saved the worldtogether for a while,and that was lovely."                  -Lost
Robert Nymanrobertnyman.com/speaking/ robnyman@mozilla.comrobertnyman.com/html5/    Twitter: @robertnymanrobertnyman.com/c...
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Upcoming SlideShare
Loading in...5
×

HTML5 APIs - Where no man has gone before! - Altran

2,186

Published on

Published in: Technology, Design

Transcript of "HTML5 APIs - Where no man has gone before! - Altran"

  1. 1. HTML5 APIs -Where No Man Has Gone Before!
  2. 2. classList
  3. 3. var elm = document.getElementById("classlist-demo");elm.classList.add("boxy");elm.classList.add("pretty");elm.classList.remove("pretty");elm.classList.toggle("pretty");elm.classList.contains("pretty");elm.classList.toString();
  4. 4. Web Storage
  5. 5. sessionStorage.setItem("FU", "Sarah Palin");console.log(sessionStorage.getItem("FU"));
  6. 6. localStorage.setItem("Job", "Politician");
  7. 7. var sarahPalin = { "contest" : "Miss Alaska pageant", "Talent" : "Flute playing"};localStorage.setItem("sarah", JSON.stringify(sarahPalin));console.log(typeof JSON.parse(localStorage.getItem("sarah")));
  8. 8. Web SQL IndexedDB
  9. 9. IndexedDB
  10. 10. // IndexedDBvar indexedDB = window.indexedDB || window.webkitIndexedDB ||window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB, IDBTransaction = window.IDBTransaction ||window.webkitIDBTransaction || window.OIDBTransaction ||window.msIDBTransaction, dbVersion = 1;// Create/open databasevar request = indexedDB.open("elephantFiles", dbVersion);
  11. 11. createObjectStore = function (dataBase) { // Create an objectStore dataBase.createObjectStore("elephants");}// Currently only in latest Firefox versionsrequest.onupgradeneeded = function (event) { createObjectStore(event.target.result);};
  12. 12. request.onsuccess = function (event) { // Create XHR var xhr = new XMLHttpRequest(), blob; xhr.open("GET", "elephant.png", true); // Set the responseType to blob xhr.responseType = "blob"; xhr.addEventListener("load", function () { if (xhr.status === 200) { // Blob as response blob = xhr.response; // Put the received blob into IndexedDB putElephantInDb(blob); } }, false); // Send XHR xhr.send();}
  13. 13. putElephantInDb = function (blob) { // Open a transaction to the database var transaction = db.transaction(["elephants"], IDBTransaction.READ_WRITE); // Put the blob into the dabase var put = transaction.objectStore("elephants").put(blob, "image"); // Retrieve the file that was just stored transaction.objectStore("elephants").get("image").onsuccess = function (event) { var imgFile = event.target.result; // Get window.URL object var URL = window.URL || window.webkitURL; // Create and revoke ObjectURL var imgURL = URL.createObjectURL(imgFile); // Set img src to ObjectURL var imgElephant = document.getElementById("elephant"); imgElephant.setAttribute("src", imgURL); // Revoking ObjectURL URL.revokeObjectURL(imgURL); };};
  14. 14. Offline Web Applications
  15. 15. if (window.addEventListener) { /* Works well in Firefox and Opera with the Work Offline option in the File menu. Pulling the ethernet cable doesnt seem to trigger it */ window.addEventListener("online", isOnline, false); window.addEventListener("offline", isOffline, false);}else { /* Works in IE with the Work Offline option in the File menu and pulling the ethernet cable */ document.body.ononline = isOnline; document.body.onoffline = isOffline;}
  16. 16. // Poll the navigator.onLine propertysetInterval(function () { console.log(navigator.onLine);}, 1000);
  17. 17. <!DOCTYPE html><html manifest="offline.appcache"><head>...
  18. 18. CACHE MANIFEST# VERSION 10CACHE:offline.htmlbase.cssFALLBACK:online.css offline.cssNETWORK:/live-updates
  19. 19. History API
  20. 20. window.history.pushState(state, title, url);
  21. 21. var url = "http://robertnyman.com",title = "My blog",state = { address : url};window.history.pushState(state, title, url);
  22. 22. Web Sockets
  23. 23. LiveConnect Forever Frame HTTP Long-Polling and XHR Streaming What came before WebSockets? AJAX HTTP PollingCross Frame Communication
  24. 24. var ws = new WebSocket("ws://robertnyman.com/wsmagic");// Send dataws.send("Some data");// Close the connectionws.close();
  25. 25. var ws = new WebSocket("ws://robertnyman.com/wsmagic");// When connection is openedws.onopen = function () { console.log("Connection opened!");};// When you receive a messagews.onmessage = function (evt) { console.log(evt.data);};// When you close the connectionws.onclose = function () { console.log("Connection closed");};// When an error occurredws.onerror = function () { console.log("An error occurred");};
  26. 26. web-socket-js Socket.IO
  27. 27. File API
  28. 28. <!-- The multiple attribute allows for uploading of multiple files--><input id="files-upload" type="file" multiple>
  29. 29. var filesUpload = document.getElementById("files-upload");filesUpload.onchange = function () { // Access to data about all files var files = this.files, file; for (var i=0, l=files.length; i<l; i++) { file = file[i]; file.name; // Get the name of the file file.size; // Get the size of the file, in bytes file.type; // Get the type of the file };};
  30. 30. for (var i=0, l=files.length, file, img; i<l; i++) { file = files[i]; if (typeof FileReader !== "undefined") { img = document.createElement("img"); reader = new FileReader(); reader.onload = (function (theImg) { return function (evt) { theImg.src = evt.target.result; }; }(img)); reader.readAsDataURL(file); }}
  31. 31. // For Firefox, Google Chrome and Safarivar xhr = new XMLHttpRequest();xhr.open("post", "upload/upload.php", true);xhr.onreadystatechange = function() { if (this.readyState === 4) { // File uploaded }};// Upload file: Firefox, Google Chrome and Safarixhr.setRequestHeader("Content-Type", "multipart/form-data");xhr.setRequestHeader("X-File-Name", file.fileName);xhr.setRequestHeader("X-File-Size", file.fileSize);xhr.setRequestHeader("X-File-Type", file.type);xhr.send(file);
  32. 32. Drag and Drop
  33. 33. ...I am forced to conclude thatthe HTML5 drag and dropmodule is not just a disaster, it’sa fucking disaster. -Peter-Paul Koch
  34. 34. <div id="can-be-dragged" draggable></div>
  35. 35. <p id="drop-area"> Drag and drop files here</p>
  36. 36. var someImg = document.getElementById("some-image"), dropArea = document.getElementById("drop-area");someImg.ondragstart = function (evt) { var event = evt || window.event; event.dataTransfer.setData("Text", this.getAttribute("alt")); return false;};dropArea.ondragenter = function (evt) { return false; “If the drop is to be}; accepted, then thisdropArea.ondragover = function (evt) { return false; event (dragover) has}; to be canceled.”dropArea.ondrop = function (evt) { var text = event.dataTransfer.getData("Text"); event.cancelBubble = true; // For IE return false;};
  37. 37. someImg.ondragstart = function (evt) { var event = evt || window.event; event.dataTransfer.setDragImage(dragIcon, -10, -10); return false;};
  38. 38. Web Workers
  39. 39. var worker = new Worker("worker.js");
  40. 40. // Main page code var worker = new Worker("worker.js"); // postMessage worker.postMessage(5); // Receive message back from Worker worker.onmessage = function (evt) { document.getElementById("worker-results").innerHTML= evt.data; }; // Error handling worker.onerror = function (evt) { document.getElementById("worker-results").innerHTML= "An error occurred"; };
  41. 41. // Web Worker codeonmessage = function (evt) { for (var i=evt.data, il=1000001; i<il; i++) { postMessage(i); };};
  42. 42. Fullscreen
  43. 43. <button id="view-fullscreen">Fullscreen</button><script type="text/javascript">(function () { var viewFullScreen = document.getElementById("view-fullscreen"); if (viewFullScreen) { viewFullScreen.addEventListener("click", function () { var docElm = document.documentElement; if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } }, false); }})(); </script>
  44. 44. mozRequestFullScreenWithKeys?
  45. 45. html:-moz-full-screen { background: red;}html:-webkit-full-screen { background: red;}
  46. 46. Camera
  47. 47. <input type="file" id="take-picture" accept="image/*">
  48. 48. takePicture.onchange = function (event) { // Get a reference to the taken picture or chosen file var files = event.target.files, file; if (files && files.length > 0) { file = files[0]; // Get window.URL object var URL = window.URL || window.webkitURL; // Create ObjectURL var imgURL = URL.createObjectURL(file); // Set img src to ObjectURL showPicture.src = imgURL; // Revoke ObjectURL URL.revokeObjectURL(imgURL); }};
  49. 49. WebRTC
  50. 50. var liveVideo = document.querySelector("#live-video");navigator.getUserMedia( {video: true}, function (stream) { liveVideo.src = stream; }, function (error) { console.log("An error occurred: " + error); });
  51. 51. Pointer Lock API
  52. 52. var docElm = document.documentElement;// Requesting Pointer LockdocElm.requestPointerLock = elem.requestPointerLock || elem.mozRequestPointerLock || elem.webkitRequestPointerLock;docElm.requestPointerLock();
  53. 53. document.addEventListener("mousemove", function(e) { var movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0, movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0; // Print the mouse movement delta values console.log("movementX=" + movementX, "movementY="+ movementY);}, false);
  54. 54. Battery
  55. 55. // Get battery level in percentagevar batteryLevel = battery.level * 100 + "%";// Get whether device is charging or notvar chargingStatus = battery.charging;// Time until the device is fully chargedvar batteryCharged = battery.chargingTime;// Time until the device is dischargedvar batteryDischarged = battery.dischargingTime;
  56. 56. battery.addEventLister("levelchange", function () { // Devices battery level changed}, false);battery.addEventListener("chargingchange", function () { // Device got plugged in to power, or unplugged}, false);battery.addEventListener("chargingtimechange", function () { // Devices charging time changed}, false);battery.addEventListener("dischargingtimechange", function () { // Devices discharging time changed}, false);
  57. 57. Try new things
  58. 58. "So we saved the worldtogether for a while,and that was lovely." -Lost
  59. 59. Robert Nymanrobertnyman.com/speaking/ robnyman@mozilla.comrobertnyman.com/html5/ Twitter: @robertnymanrobertnyman.com/css3/
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×