(click anywhere to close)

[JavaScript] HTML5 APIs

category: Website | course: Advanced Javascript | difficulty:

As part of the new HTML5 standard, 6 very useful APIs were added to JavaScript. These are somewhat specific, as they were invented for a few exact purposes, and therefore perfect if one of those purposes is your goal. With careful implementation though, you can build great things out of them!


The geolocation property of the browser window navigator is used to retrieve the user’s location. Since this is privacy related, the user has to approve. To get this location, we use the

getCurrentPosition(success, failure)

method. It takes the names of two functions, of which the first one is called when geolocation was successful, and the second when it wasn’t. The success function automatically receives one argument, which is the position, and the failure function receives the error.

function suc(pos) {
	console.log("Your position is " + pos);
function fail() {
	console.log("Everything Failed!");

Such a position is an object with the following properties:




Latitude as a decimal number


Longitude as a decimal number


Accuracy of the position (depends on accuracy of GPS within device)


Altitude in meters above the mean sea level


Accuracy of the altitude


Orientation as degrees clockwise from North


Speed in meters per second


The date ( = time) of the response

function suc(pos) {
	console.log("Your altitude is " + pos.coords.altitude);
function fail() {
	console.log("Everything Failed!");

Other methods available are watchPosition(success, failure) to keep updating the user’s position as it moves, and clearWatch() to stop watching.

Drag & Drop

The ability to drag and drop elements can be simulated, but with this API it’s built right into JavaScript. First, you need to set the draggable=true attribute on the element you want to drag, and add a dragstart event. Then, you need to tell your dropping element to react to drop and dragover events.

All these events share a property, which is dataTransfer, and you can use setData(name, data) to set which data to transfer, and getData(name) to retrieve it as you drop something.

function allowDrop(ev) {

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);

function drop(ev) {
    var data = ev.dataTransfer.getData("text");
<div id="dropZone" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<img id="dragThing" src="someImage.png" draggable="true"

Because by default, elements can’t just be dragged and dropped around, we need to use preventDefault() to prevent this default behaviour when we do want drag-n-drop abilities.

Local Storage

Cookies provide a way to store very small bits of data. Local storage expands on this, and makes it much easier to save large amounts of data within the browser. This data is not tied to a certain URL, but rather to a certain name you give it.

To add an entry to the local storage, use

localStorage.setItem(name, value)

To retrieve one, use


These have no expiration date – which means it remains saved until you decide to remove it. If you only want to save data for one session, use sessionStorage instead. A session begins when a browser tab is opened, and ends when it is closed.

//Some time later...
var x = localStorage.getItem("Username"); //x is Juan

App Cache

App Cache allows us to cache a web app, which means saving an offline version, which means it can be accessed and used without internet connection. Not only does this allow users to work with it when there’s no internet around, it also increases speed and reduces server load.

The parts you want the browser to cache are saved in a cache manifest file. Such a file can simply be created in your text editor, and required the extension .appcache.

Then, within the HTML tag, you need to set the manifest attribute to point to your file.

<html manifest="someFile.appcache">

Manifest files contain three sections, which need to be named explicitly to tell the browser it’s in that section now.

  • CACHE MANIFEST: Underneath it, specify the files you want to be cached after they are downloaded the first time
  • NETWORK: Underneath it, specify the files you never want to be cached.
  • FALLBACK: Underneath it, specify which file to serve instead of others if an internet connection cannot be established.
# Manifest of 18 December 2015


/someFolder/ /defaultPage.html

Once cached, the browser will load the offline version. To tell it to update, change the manifest file by adding a random new comment. Comments are made with the syntax # comment

To select all files, use the familiar asterisk ( * )

There are size limits, but they depend on the browser, which means you shouldn’t go wild with app caches.

Web Workers

Web workers are scripts running in the background, without influencing the rest of the page. This means that it doesn’t halt execution of the main script, nor affect performance. Great!

To create a new web worker, use the constructor:

new Worker(“pathtofile.js”)

As soon as it’s created, it executes the code within the file you referenced. Such an external file and the script it was created in communicate by means of messages.

Within the external file, you can use postMessage(message) to post a message. This message can be acted on by adding an event listener for the message event, which, as usual, takes the event as argument. Using the data property we can access the message that was sent by the web worker.

//Inside external web worker file
function timedCount() {

var i = 0;
//Main script
var w = new Worker("externalFile.js");
w.onmessage = function(event){
    console.log(event.data); //Prints the current count to the console, every second

To terminate a web worker, simply call the terminate() method.

Because Web Workers are essentially external scripts running, they can’t access the window, document or parent object.

Server-Sent Events

Server-Sent Events, or SSEs, are messages sent from a server. It’s one way traffic, as the web page automatically receives updates from the server, but doesn’t send anything back.

To create a new SSE, use

new EventSource(“pathtofile.php”)

You can use any server language you want, but this example will use the most common one, PHP. Just as with web workers, the communication works via messages, and JavaScript uses the message event to listen for them.

var someSource = new EventSource("externalFile.php");
someSource.onmessage = function(event) {

Sending the messages, however, works a bit different. Within the PHP file, we need to specify what type of content is coming, and then echo our message with data: in front. Finally, the flush() command sends whatever’s on the page at that moment back to the script.

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

echo "data: This is a cool message!";

Additionally, the open event fires when a server connection has been opened, and the error event occurs when opening such connection failed.

Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk