HTML5 APIs - Where no man has gone before! - Altran
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,538
On Slideshare
2,535
From Embeds
3
Number of Embeds
2

Actions

Shares
Downloads
40
Comments
0
Likes
5

Embeds 3

https://www.linkedin.com 2
http://yomaragavilanes.blogspot.com 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. HTML5 APIs -Where No Man Has Gone Before!
  • 2. classList
  • 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. Web Storage
  • 5. sessionStorage.setItem("FU", "Sarah Palin");console.log(sessionStorage.getItem("FU"));
  • 6. localStorage.setItem("Job", "Politician");
  • 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. Web SQL IndexedDB
  • 9. IndexedDB
  • 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. createObjectStore = function (dataBase) { // Create an objectStore dataBase.createObjectStore("elephants");}// Currently only in latest Firefox versionsrequest.onupgradeneeded = function (event) { createObjectStore(event.target.result);};
  • 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. 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. Offline Web Applications
  • 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. // Poll the navigator.onLine propertysetInterval(function () { console.log(navigator.onLine);}, 1000);
  • 17. <!DOCTYPE html><html manifest="offline.appcache"><head>...
  • 18. CACHE MANIFEST# VERSION 10CACHE:offline.htmlbase.cssFALLBACK:online.css offline.cssNETWORK:/live-updates
  • 19. History API
  • 20. window.history.pushState(state, title, url);
  • 21. var url = "http://robertnyman.com",title = "My blog",state = { address : url};window.history.pushState(state, title, url);
  • 22. Web Sockets
  • 23. LiveConnect Forever Frame HTTP Long-Polling and XHR Streaming What came before WebSockets? AJAX HTTP PollingCross Frame Communication
  • 24. var ws = new WebSocket("ws://robertnyman.com/wsmagic");// Send dataws.send("Some data");// Close the connectionws.close();
  • 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. web-socket-js Socket.IO
  • 27. File API
  • 28. <!-- The multiple attribute allows for uploading of multiple files--><input id="files-upload" type="file" multiple>
  • 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. 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. // 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. Drag and Drop
  • 33. ...I am forced to conclude thatthe HTML5 drag and dropmodule is not just a disaster, it’sa fucking disaster. -Peter-Paul Koch
  • 34. <div id="can-be-dragged" draggable></div>
  • 35. <p id="drop-area"> Drag and drop files here</p>
  • 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. someImg.ondragstart = function (evt) { var event = evt || window.event; event.dataTransfer.setDragImage(dragIcon, -10, -10); return false;};
  • 38. Web Workers
  • 39. var worker = new Worker("worker.js");
  • 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. // Web Worker codeonmessage = function (evt) { for (var i=evt.data, il=1000001; i<il; i++) { postMessage(i); };};
  • 42. Fullscreen
  • 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. mozRequestFullScreenWithKeys?
  • 45. html:-moz-full-screen { background: red;}html:-webkit-full-screen { background: red;}
  • 46. Camera
  • 47. <input type="file" id="take-picture" accept="image/*">
  • 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. WebRTC
  • 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. Pointer Lock API
  • 52. var docElm = document.documentElement;// Requesting Pointer LockdocElm.requestPointerLock = elem.requestPointerLock || elem.mozRequestPointerLock || elem.webkitRequestPointerLock;docElm.requestPointerLock();
  • 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. Battery
  • 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. 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. Try new things
  • 58. "So we saved the worldtogether for a while,and that was lovely." -Lost
  • 59. Robert Nymanrobertnyman.com/speaking/ robnyman@mozilla.comrobertnyman.com/html5/ Twitter: @robertnymanrobertnyman.com/css3/