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

Transcript
Page 1: HTML5 APIs - Where no man has gone before! - Altran

HTML5 APIs - Where No Man Has

Gone Before!

Page 2: HTML5 APIs - Where no man has gone before! - Altran
Page 3: HTML5 APIs - Where no man has gone before! - Altran
Page 5: HTML5 APIs - Where no man has gone before! - Altran

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();

Page 7: HTML5 APIs - Where no man has gone before! - Altran

sessionStorage.setItem("FU", "Sarah Palin");console.log(sessionStorage.getItem("FU"));

Page 8: HTML5 APIs - Where no man has gone before! - Altran

localStorage.setItem("Job", "Politician");

Page 9: HTML5 APIs - Where no man has gone before! - Altran

var sarahPalin = { "contest" : "Miss Alaska pageant", "Talent" : "Flute playing"};

localStorage.setItem("sarah", JSON.stringify(sarahPalin));

console.log(typeof JSON.parse(localStorage.getItem("sarah")));

Page 10: HTML5 APIs - Where no man has gone before! - Altran

IndexedDBWeb SQL

Page 12: HTML5 APIs - Where no man has gone before! - Altran

// 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);

Page 13: HTML5 APIs - Where no man has gone before! - Altran

createObjectStore = function (dataBase) { // Create an objectStore dataBase.createObjectStore("elephants");}

// Currently only in latest Firefox versionsrequest.onupgradeneeded = function (event) { createObjectStore(event.target.result);};

Page 14: HTML5 APIs - Where no man has gone before! - Altran

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();}

Page 15: HTML5 APIs - Where no man has gone before! - Altran

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); };};

Page 17: HTML5 APIs - Where no man has gone before! - Altran

if (window.addEventListener) { /* Works well in Firefox and Opera with the Work Offline option in the File menu. Pulling the ethernet cable doesn't 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;}

Page 18: HTML5 APIs - Where no man has gone before! - Altran

// Poll the navigator.onLine propertysetInterval(function () { console.log(navigator.onLine);}, 1000);

Page 19: HTML5 APIs - Where no man has gone before! - Altran

<!DOCTYPE html><html manifest="offline.appcache"><head>...

Page 20: HTML5 APIs - Where no man has gone before! - Altran
Page 21: HTML5 APIs - Where no man has gone before! - Altran

CACHE MANIFEST

# VERSION 10

CACHE:offline.htmlbase.css

FALLBACK:online.css offline.css

NETWORK:/live-updates

Page 23: HTML5 APIs - Where no man has gone before! - Altran

window.history.pushState(state, title, url);

Page 24: HTML5 APIs - Where no man has gone before! - Altran

var url = "http://robertnyman.com",title = "My blog",state = { address : url};

window.history.pushState(state, title, url);

Page 27: HTML5 APIs - Where no man has gone before! - Altran

What came before WebSockets?

Cross Frame Communication

HTTP Polling

LiveConnectForever Frame

AJAX

HTTP Long-Polling and XHR Streaming

Page 28: HTML5 APIs - Where no man has gone before! - Altran

var ws = new WebSocket("ws://robertnyman.com/wsmagic");

// Send dataws.send("Some data");

// Close the connectionws.close();

Page 29: HTML5 APIs - Where no man has gone before! - Altran

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 occurred ws.onerror = function () { console.log("An error occurred");};

Page 31: HTML5 APIs - Where no man has gone before! - Altran

File API

Page 32: HTML5 APIs - Where no man has gone before! - Altran

<!-- The multiple attribute allows for uploading of multiple files--><input id="files-upload" type="file" multiple>

Page 33: HTML5 APIs - Where no man has gone before! - Altran

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

Page 34: HTML5 APIs - Where no man has gone before! - Altran

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); }}

Page 35: HTML5 APIs - Where no man has gone before! - Altran

// 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);

Page 36: HTML5 APIs - Where no man has gone before! - Altran

Drag and Drop

Page 37: HTML5 APIs - Where no man has gone before! - Altran

...I am forced to conclude that the HTML5 drag and drop module is not just a disaster, it’s a fucking disaster.

-Peter-Paul Koch

Page 38: HTML5 APIs - Where no man has gone before! - Altran

<div id="can-be-dragged" draggable></div>

Page 39: HTML5 APIs - Where no man has gone before! - Altran

<p id="drop-area"> Drag and drop files here</p>

Page 40: HTML5 APIs - Where no man has gone before! - Altran

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

dropArea.ondragover = function (evt) { return false;};

dropArea.ondrop = function (evt) { var text = event.dataTransfer.getData("Text"); event.cancelBubble = true; // For IE return false;};

“If the drop is to be accepted, then this

event (dragover) has to be canceled.”

Page 41: HTML5 APIs - Where no man has gone before! - Altran

someImg.ondragstart = function (evt) { var event = evt || window.event; event.dataTransfer.setDragImage(dragIcon, -10, -10); return false;};

Page 42: HTML5 APIs - Where no man has gone before! - Altran

Web Workers

Page 43: HTML5 APIs - Where no man has gone before! - Altran

var worker = new Worker("worker.js");

Page 44: HTML5 APIs - Where no man has gone before! - Altran

// 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"; };

Page 45: HTML5 APIs - Where no man has gone before! - Altran

// Web Worker code onmessage = function (evt) { for (var i=evt.data, il=1000001; i<il; i++) { postMessage(i); }; };

Page 47: HTML5 APIs - Where no man has gone before! - Altran
Page 48: HTML5 APIs - Where no man has gone before! - Altran
Page 49: HTML5 APIs - Where no man has gone before! - Altran

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

Page 50: HTML5 APIs - Where no man has gone before! - Altran

mozRequestFullScreenWithKeys?

Page 51: HTML5 APIs - Where no man has gone before! - Altran

html:-moz-full-screen { background: red;}

html:-webkit-full-screen { background: red;}

Page 53: HTML5 APIs - Where no man has gone before! - Altran
Page 54: HTML5 APIs - Where no man has gone before! - Altran

<input type="file" id="take-picture" accept="image/*">

Page 55: HTML5 APIs - Where no man has gone before! - Altran

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); }};

Page 57: HTML5 APIs - Where no man has gone before! - Altran

var liveVideo = document.querySelector("#live-video");navigator.getUserMedia( {video: true}, function (stream) { liveVideo.src = stream; }, function (error) { console.log("An error occurred: " + error); });

Page 59: HTML5 APIs - Where no man has gone before! - Altran

var docElm = document.documentElement; // Requesting Pointer LockdocElm.requestPointerLock = elem.requestPointerLock || elem.mozRequestPointerLock || elem.webkitRequestPointerLock; docElm.requestPointerLock();

Page 60: HTML5 APIs - Where no man has gone before! - Altran

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

Page 63: HTML5 APIs - Where no man has gone before! - Altran
Page 64: HTML5 APIs - Where no man has gone before! - Altran

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

Page 65: HTML5 APIs - Where no man has gone before! - Altran

battery.addEventLister("levelchange", function () { // Device's battery level changed}, false);

battery.addEventListener("chargingchange", function () { // Device got plugged in to power, or unplugged}, false);

battery.addEventListener("chargingtimechange", function () { // Device's charging time changed}, false);

battery.addEventListener("dischargingtimechange", function () { // Device's discharging time changed}, false);

Page 66: HTML5 APIs - Where no man has gone before! - Altran

Try new things

Page 67: HTML5 APIs - Where no man has gone before! - Altran
Page 69: HTML5 APIs - Where no man has gone before! - Altran
Page 72: HTML5 APIs - Where no man has gone before! - Altran

"So we saved the world together for a while, and that was lovely."

-Lost