5 - HTML5 JavaScript APIs

Michel Buffa
April 2014

buffa@unice.fr

Additions to the DOM JavaScript API

getElementsByClassName()

var list1 = document.getElementsByClassName('important');
for (var i = 0; i < list1.length; i++) {
 // do something with list1.item(i) or list1[i],
 // in our case : put the background in red
 list1[i].style.backgroundColor = 'red';
}

var elem1= document.getElementById('id1').
               getElementsByClassName('notImportant');

Additions to the DOM JavaScript API

querySelector() and querySelectorAll() and matches() bring CSS selectors to the DOM API

Example: get all <li> elements in a <ul> of class "nav":

<ul class="nav">
   <li><a href="/">Home</a></li>
   <li><a href="/products">Products</a></li>
   <li><a href="/about">About</a></li>
 </ul>

// get all <li> directly in a <ul> of class nav
var list = document.querySelectorAll("ul.nav > li");

for (var i = 0; i < list.length; i++) {
     process(list[i]); // do something with each of the li elems...
 }

Additions to the DOM JavaScript API

The classlist interface

Example: get all <li> elements in a <ul> of class "nav":

var elem= document.getDocumentById("id1");
var allClasses = elem.classList;

Méthods of the classlist interface: add(), remove(), toggle() and contains()

// Set "foo" as the class by adding it to the classList
div.classList.add('foo'); // now <div class="foo"/>
// Check that the classList contains the class "foo"
div.classList.contains('foo'); // returns true
// Remove the class "foo" from the list
div.classList.remove('foo'); // now <div class=""/>
Geolocation

Geolocation example

Geolocation: a few lines of code !

var displayCoords=document.getElementById("msg");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    displayCoords.innerHTML="Geolocation API not supported !";
  }
}

function showPosition(position) {
  displayCoords.innerHTML="Latitude: " + position.coords.latitude +
"<br />Longitude: " + position.coords.longitude;
}
                

Properties of the coords object

Example with the google reverse geocoder

Example with a form that auto fills the address fields using geolocation

The orientation API

Coordinate system

Typical code

    if (window.DeviceOrientationEvent) {
        console.log("DeviceOrientation is supported");

        window.addEventListener('deviceorientation',
          function (eventData) {
            var LR = eventData.gamma; // / backLeft/right
            var FB = eventData.beta;  // front
            var DIR = eventData.alpha; // direction
            // do something h wit
        }, false);
    } else {
        alert("Device orientation not supported on your device or browser.  Sorry.");
    }
    

Demo: a Level Tool.

Variant : the Device Motion API

Works with acceleration instead of orientation. Useful for games, etc.

The acceleration is in three parts, acceleration along the X axis, the Y axis and the Z axis. Each value is in meters per second squared (m/s^2)

function handleMotionEvent(event) {

    var x = event.accelerationIncludingGravity.x;
    var y = event.accelerationIncludingGravity.y;
    var z = event.accelerationIncludingGravity.z;

    // Process ...
}

window.addEventListener("devicemotion", handleMotionEvent, true);
        

Web workers: threads in JavaScript


<p>The highest prime number discovered so far is: <output id="result"></output></p>
<script>
   var worker = new Worker('worker.js');

   worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
   };
</script>
        

Code from the worker of the previous example

var n = 1;
search: while (true) {
  n += 1;
  for (var i = 2; i <= Math.sqrt(n); i += 1)
    if (n % i == 0)
     continue search;
  // found a prime!
  postMessage(n);
}            
        

Workers cannot access the DOM, they communicate with creator using messages/events

There are two sorts of WebWorkers, only first type (the one presented) has stable specification.

HTML5 WebSockets

Full duplex, bidirectional realtime communication channel,

Share HTTP ports used by HTTP server

Traverse firewalls

Keep the connection open

Adds only 2 bytes per frame (data between 0x00 and 0xFF)

Data encoded in UTF-8 (no binary!)

Bye bye Flash Sockets!

Connexion: HTTP handshake


The WebSocket API

var ws = new WebSocket("ws://host:port");

ws.onopen = function(evt) { alert("Connection open!"); };

ws.onmessage = function(evt) { alert( "Received message: " + evt.data); };

ws.onclose = function(evt) { alert("Connection closed."); };

ws.onerror = function(evt) { alert("WebSocket error : " + evt.data) };

ws.send(MyMessage);

ws.close();
                

Examples and demos use: NodeJS + socket.io + express

socket.io (JavaScipt)

  • Module for NodeJS, very popular,
  • Fallbacks if WebSockets not supported (Flash Sockets, Comet, Ajax...),
  • Handle deconnexions/reconnexions
  • Handle server side sessions, (aka game rooms)
  • Functions for sending data from server to one client, to all clients, to all clients except emitter
  • JavaScript objects are automatically converted to JSON

Lab Exercises for this tutorial include the study of two complete chat applications that use socket.io

The chat is the one included in all the next demos,

We just send JavaScript Objects (positions, etc.) over the same channel.

Starting from this small example, Michel Buffa's master students from the University of Nice (France) wrote this game

Some demos

Web Sockets and orientation API