SlideShare a Scribd company logo
HTML5 APIs -
Where No Man Has
  Gone Before!
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
classList
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();
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.stringify(sarahPalin));

console.log(typeof JSON.parse(localStorage.getItem("sarah")));
Web SQL   IndexedDB
IndexedDB
// IndexedDB
var indexedDB = window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
    IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.OIDBTransaction ||
window.msIDBTransaction,
    dbVersion = 1;

// Create/open database
var request = indexedDB.open("elephantFiles", dbVersion);
createObjectStore = function (dataBase) {
    // Create an objectStore
    dataBase.createObjectStore("elephants");
}

// Currently only in latest Firefox versions
request.onupgradeneeded = function (event) {
    createObjectStore(event.target.result);
};
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();
}
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);
     };
};
Offline Web Applications
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;
}
// Poll the navigator.onLine property
setInterval(function () {
    console.log(navigator.onLine);
}, 1000);
<!DOCTYPE html>
<html manifest="offline.appcache">
<head>
...
HTML5 APIs - Where no man has gone before! - Altran
CACHE MANIFEST

# VERSION 10

CACHE:
offline.html
base.css

FALLBACK:
online.css offline.css

NETWORK:
/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, url);
HTML5 APIs - Where no man has gone before! - Altran
Web Sockets
LiveConnect
    Forever Frame



      HTTP Long-Polling and XHR Streaming




    What came before WebSockets?

      AJAX
                                            HTTP Polling



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

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

// Close the connection
ws.close();
var ws = new WebSocket("ws://robertnyman.com/wsmagic");

// When connection is opened
ws.onopen = function () {
    console.log("Connection opened!");
};

// When you receive a message
ws.onmessage = function (evt) {
    console.log(evt.data);
};

// When you close the connection
ws.onclose = function () {
    console.log("Connection closed");
};

// When an error occurred
ws.onerror = function () {
    console.log("An error occurred");
};
web-socket-js
 Socket.IO
File API
<!--
       The multiple attribute allows for
       uploading of multiple files
-->
<input id="files-upload" type="file" multiple>
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
    };
};
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);
    }
}
// For Firefox, Google Chrome and Safari
var 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 Safari
xhr.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);
Drag and Drop
...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
<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.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 this
dropArea.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;
};
someImg.ondragstart = function (evt) {
    var event = evt || window.event;
    event.dataTransfer.setDragImage(dragIcon, -10, -10);
    return false;
};
Web Workers
var worker = new Worker("worker.js");
// 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";
    };
// Web Worker code
onmessage = function (evt) {
    for (var i=evt.data, il=1000001; i<il; i++) {
        postMessage(i);
    };
};
Fullscreen
HTML5 APIs - Where no man has gone before! - Altran
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>
mozRequestFullScreenWithKeys?
html:-moz-full-screen {
    background: red;
}

html:-webkit-full-screen {
    background: red;
}
Camera
HTML5 APIs - Where no man has gone before! - Altran
<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.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);
     }
};
WebRTC
var liveVideo = document.querySelector("#live-video");
navigator.getUserMedia(
    {video: true},
    function (stream) {
        liveVideo.src = stream;
    },
    function (error) {
        console.log("An error occurred: " + error);
    }
);
Pointer Lock API
var docElm = document.documentElement;

// Requesting Pointer Lock
docElm.requestPointerLock = elem.requestPointerLock ||
                             elem.mozRequestPointerLock ||
                             elem.webkitRequestPointerLock;
docElm.requestPointerLock();
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);
HTML5 APIs - Where no man has gone before! - Altran
Battery
HTML5 APIs - Where no man has gone before! - Altran
// Get battery level in percentage
var batteryLevel = battery.level * 100 + "%";

// Get whether device is charging or not
var chargingStatus = battery.charging;

// Time until the device is fully charged
var batteryCharged = battery.chargingTime;

// Time until the device is discharged
var batteryDischarged = battery.dischargingTime;
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);
Try new things
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
"So we saved the world
together for a while,
and that was lovely."
                  -Lost
Robert Nyman
robertnyman.com/speaking/ robnyman@mozilla.com
robertnyman.com/html5/    Twitter: @robertnyman
robertnyman.com/css3/

More Related Content

What's hot (20)

PDF
Leave No One Behind with HTML5 - FFWD.PRO, Croatia
Robert Nyman
 
PDF
Web Crawling with NodeJS
Sylvain Zimmer
 
PDF
HTML5 & The Open Web - at Nackademin
Robert Nyman
 
PDF
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
PDF
JavaScript Promise
Joseph Chiang
 
PDF
JavaScript APIs - The Web is the Platform
Robert Nyman
 
PDF
HTML5 APIs - Where No Man Has Gone Before! - Paris Web
Robert Nyman
 
PDF
async/await in Swift
Peter Friese
 
PPTX
jQuery Data Manipulate API - A source code dissecting journey
Huiyi Yan
 
PDF
JavaScript and HTML5 - Brave New World (revised)
Robert Nyman
 
PDF
JavaScript & HTML5 - Brave New World
Robert Nyman
 
PDF
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
Robert Nyman
 
PDF
HTML5: where flash isn't needed anymore
Remy Sharp
 
PPTX
Bare-knuckle web development
Johannes Brodwall
 
PPT
jQuery 1.7 Events
dmethvin
 
PDF
Tinkerbelles return home from their Guinness world-record attempt on Sunday
chicagonewsyesterday
 
PDF
Introduction to ECMAScript 2015
Tomasz Dziuda
 
PPTX
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
PDF
Promise pattern
Sebastiaan Deckers
 
PDF
HTML,CSS Next
지수 윤
 
Leave No One Behind with HTML5 - FFWD.PRO, Croatia
Robert Nyman
 
Web Crawling with NodeJS
Sylvain Zimmer
 
HTML5 & The Open Web - at Nackademin
Robert Nyman
 
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
JavaScript Promise
Joseph Chiang
 
JavaScript APIs - The Web is the Platform
Robert Nyman
 
HTML5 APIs - Where No Man Has Gone Before! - Paris Web
Robert Nyman
 
async/await in Swift
Peter Friese
 
jQuery Data Manipulate API - A source code dissecting journey
Huiyi Yan
 
JavaScript and HTML5 - Brave New World (revised)
Robert Nyman
 
JavaScript & HTML5 - Brave New World
Robert Nyman
 
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
Robert Nyman
 
HTML5: where flash isn't needed anymore
Remy Sharp
 
Bare-knuckle web development
Johannes Brodwall
 
jQuery 1.7 Events
dmethvin
 
Tinkerbelles return home from their Guinness world-record attempt on Sunday
chicagonewsyesterday
 
Introduction to ECMAScript 2015
Tomasz Dziuda
 
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
Promise pattern
Sebastiaan Deckers
 
HTML,CSS Next
지수 윤
 

Similar to HTML5 APIs - Where no man has gone before! - Altran (20)

PDF
The Beauty Of Java Script V5a
rajivmordani
 
PDF
The Beauty of Java Script
Michael Girouard
 
KEY
Week 4 - jQuery + Ajax
baygross
 
PDF
Javascript Frameworks for Joomla
Luke Summerfield
 
KEY
Paris js extensions
erwanl
 
PDF
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Robert Nyman
 
PDF
Websockets talk at Rubyconf Uruguay 2010
Ismael Celis
 
PDF
jQuery secrets
Bastian Feder
 
KEY
JavaScript Testing for Rubyists
Jamie Dyer
 
PDF
JavaScript - Like a Box of Chocolates - jsDay
Robert Nyman
 
PPTX
Coding using jscript test complete
Viresh Doshi
 
PDF
jQuery secrets
Bastian Feder
 
KEY
BlackBerry DevCon 2011 - PhoneGap and WebWorks
mwbrooks
 
PPTX
Beyond the page
Glenn Jones
 
PDF
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
PPTX
NodeJs
dizabl
 
PDF
JavaScript - Like a Box of Chocolates
Robert Nyman
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
The Beauty Of Java Script V5a
rajivmordani
 
The Beauty of Java Script
Michael Girouard
 
Week 4 - jQuery + Ajax
baygross
 
Javascript Frameworks for Joomla
Luke Summerfield
 
Paris js extensions
erwanl
 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Robert Nyman
 
Websockets talk at Rubyconf Uruguay 2010
Ismael Celis
 
jQuery secrets
Bastian Feder
 
JavaScript Testing for Rubyists
Jamie Dyer
 
JavaScript - Like a Box of Chocolates - jsDay
Robert Nyman
 
Coding using jscript test complete
Viresh Doshi
 
jQuery secrets
Bastian Feder
 
BlackBerry DevCon 2011 - PhoneGap and WebWorks
mwbrooks
 
Beyond the page
Glenn Jones
 
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
NodeJs
dizabl
 
JavaScript - Like a Box of Chocolates
Robert Nyman
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Ad

More from Robert Nyman (20)

PDF
Have you tried listening?
Robert Nyman
 
PDF
Building for Your Next Billion - Google I/O 2017
Robert Nyman
 
PDF
Introduction to Google Daydream
Robert Nyman
 
PDF
Predictability for the Web
Robert Nyman
 
PDF
The Future of Progressive Web Apps - View Source conference, Berlin 2016
Robert Nyman
 
PDF
The Future of the Web - Cold Front conference 2016
Robert Nyman
 
PDF
The Future of Progressive Web Apps - Google for Indonesia
Robert Nyman
 
PDF
Google tech & products
Robert Nyman
 
PDF
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Robert Nyman
 
PDF
Progressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
Robert Nyman
 
PDF
The web - What it has, what it lacks and where it must go - keynote at Riga D...
Robert Nyman
 
PDF
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
Robert Nyman
 
PDF
The web - What it has, what it lacks and where it must go - Istanbul
Robert Nyman
 
PDF
The web - What it has, what it lacks and where it must go
Robert Nyman
 
PDF
Google, the future and possibilities
Robert Nyman
 
PDF
Developer Relations in the Nordics
Robert Nyman
 
PDF
What is Developer Relations?
Robert Nyman
 
PDF
Android TV Introduction - Stockholm Android TV meetup
Robert Nyman
 
PDF
New improvements for web developers - frontend.fi, Helsinki
Robert Nyman
 
PDF
Mobile phone trends, user data & developer climate - frontend.fi, Helsinki
Robert Nyman
 
Have you tried listening?
Robert Nyman
 
Building for Your Next Billion - Google I/O 2017
Robert Nyman
 
Introduction to Google Daydream
Robert Nyman
 
Predictability for the Web
Robert Nyman
 
The Future of Progressive Web Apps - View Source conference, Berlin 2016
Robert Nyman
 
The Future of the Web - Cold Front conference 2016
Robert Nyman
 
The Future of Progressive Web Apps - Google for Indonesia
Robert Nyman
 
Google tech & products
Robert Nyman
 
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Robert Nyman
 
Progressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
Robert Nyman
 
The web - What it has, what it lacks and where it must go - keynote at Riga D...
Robert Nyman
 
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
Robert Nyman
 
The web - What it has, what it lacks and where it must go - Istanbul
Robert Nyman
 
The web - What it has, what it lacks and where it must go
Robert Nyman
 
Google, the future and possibilities
Robert Nyman
 
Developer Relations in the Nordics
Robert Nyman
 
What is Developer Relations?
Robert Nyman
 
Android TV Introduction - Stockholm Android TV meetup
Robert Nyman
 
New improvements for web developers - frontend.fi, Helsinki
Robert Nyman
 
Mobile phone trends, user data & developer climate - frontend.fi, Helsinki
Robert Nyman
 
Ad

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 

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

  • 1. HTML5 APIs - Where No Man Has Gone Before!
  • 5. 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();
  • 9. var sarahPalin = { "contest" : "Miss Alaska pageant", "Talent" : "Flute playing" }; localStorage.setItem("sarah", JSON.stringify(sarahPalin)); console.log(typeof JSON.parse(localStorage.getItem("sarah")));
  • 10. Web SQL IndexedDB
  • 12. // IndexedDB var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB, IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction, dbVersion = 1; // Create/open database var request = indexedDB.open("elephantFiles", dbVersion);
  • 13. createObjectStore = function (dataBase) { // Create an objectStore dataBase.createObjectStore("elephants"); } // Currently only in latest Firefox versions request.onupgradeneeded = function (event) { createObjectStore(event.target.result); };
  • 14. 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(); }
  • 15. 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); }; };
  • 17. 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; }
  • 18. // Poll the navigator.onLine property setInterval(function () { console.log(navigator.onLine); }, 1000);
  • 21. CACHE MANIFEST # VERSION 10 CACHE: offline.html base.css FALLBACK: online.css offline.css NETWORK: /live-updates
  • 24. var url = "http://robertnyman.com", title = "My blog", state = { address : url }; window.history.pushState(state, title, url);
  • 27. LiveConnect Forever Frame HTTP Long-Polling and XHR Streaming What came before WebSockets? AJAX HTTP Polling Cross Frame Communication
  • 28. var ws = new WebSocket("ws://robertnyman.com/wsmagic"); // Send data ws.send("Some data"); // Close the connection ws.close();
  • 29. var ws = new WebSocket("ws://robertnyman.com/wsmagic"); // When connection is opened ws.onopen = function () { console.log("Connection opened!"); }; // When you receive a message ws.onmessage = function (evt) { console.log(evt.data); }; // When you close the connection ws.onclose = function () { console.log("Connection closed"); }; // When an error occurred ws.onerror = function () { console.log("An error occurred"); };
  • 32. <!-- The multiple attribute allows for uploading of multiple files --> <input id="files-upload" type="file" multiple>
  • 33. 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 }; };
  • 34. 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); } }
  • 35. // For Firefox, Google Chrome and Safari var 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 Safari xhr.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);
  • 37. ...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
  • 39. <p id="drop-area"> Drag and drop files here </p>
  • 40. 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 this dropArea.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; };
  • 41. someImg.ondragstart = function (evt) { var event = evt || window.event; event.dataTransfer.setDragImage(dragIcon, -10, -10); return false; };
  • 43. var worker = new Worker("worker.js");
  • 44. // 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"; };
  • 45. // Web Worker code onmessage = function (evt) { for (var i=evt.data, il=1000001; i<il; i++) { postMessage(i); }; };
  • 49. <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>
  • 51. html:-moz-full-screen { background: red; } html:-webkit-full-screen { background: red; }
  • 55. 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); } };
  • 57. var liveVideo = document.querySelector("#live-video"); navigator.getUserMedia( {video: true}, function (stream) { liveVideo.src = stream; }, function (error) { console.log("An error occurred: " + error); } );
  • 59. var docElm = document.documentElement; // Requesting Pointer Lock docElm.requestPointerLock = elem.requestPointerLock || elem.mozRequestPointerLock || elem.webkitRequestPointerLock; docElm.requestPointerLock();
  • 60. 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);
  • 64. // Get battery level in percentage var batteryLevel = battery.level * 100 + "%"; // Get whether device is charging or not var chargingStatus = battery.charging; // Time until the device is fully charged var batteryCharged = battery.chargingTime; // Time until the device is discharged var batteryDischarged = battery.dischargingTime;
  • 65. 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);
  • 72. "So we saved the world together for a while, and that was lovely." -Lost