Foreword

An application programming interface (API) is a series of “hooks” built in to an application that allows external access to the application’s data and functionality.


 








 







HTML5 Geolocation


HTML Geolocation is used to locate a user's position.


Locate the User's Position

The HTML Geolocation API is used to get the geographical position of a user.

Since this can compromise user privacy, the position is not available unless the user approves it.


Browser Support

The numbers in the table specify the first browser version that fully supports Geolocation.

API
Geolocation 5.0 9.0 3.5 5.0 16.0

Note: Geolocation is much more accurate for devices with GPS, like iPhone.


Using HTML Geolocation

Use the getCurrentPosition() method to get the user's position.

The example below is a simple Geolocation example returning the latitude and longitude of the user's position:

Example

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>
Not Available

Example explained:

The example above is a very basic Geolocation script, with no error handling.


Handling Errors and Rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

Example

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "the request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
Not Available

Error Codes:


Displaying the Result in a Map

To display the result in a map, you need access to a map service that can use latitude and longitude, like Google Maps:

Example

function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=
    "+latlon+"&zoom=14&size=400x300 &sensor=false";

    document.getElementById("mapholder").innerHTML = "< img src='"+img_url+"'>";
}
Not Available

In the example above we use the returned latitude and longitude data to show the location in a Google map (using a static image).

Another example for Geolocation would be a Google Map script that would show an interactive map with a marker, zoom and drag options.


Location-specific Information

this page demonstrated how to show a user's position on a map. However, Geolocation is also very useful for location-specific information.

Examples:


the getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object if it is successful. the latitude, longitude and accuracy properties are always returned. the other properties below are returned if available.

Property Description
coords.latitude the latitude as a decimal number
coords.longitude the longitude as a decimal number
coords.accuracy the accuracy of position
coords.altitude the altitude in meters above the mean sea level
coords.altitudeAccuracy the altitude accuracy of position
coords.heading the heading as degrees clockwise from North
coords.speed the speed in meters per second
timestamp the date/time of the response

Geolocation object - Other interesting Methods

watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).

clearWatch() - Stops the watchPosition() method.

The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):

Example

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition (showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>
Not Available

 







HTML5 Drag and Drop

Drag and drop is a part of the HTML5 standard.


HTML 201

Drag the HTML 201 image into the rectangle.


Drag and Drop

Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.

In HTML5, drag and drop is part of the standard, and any element can be draggable.


Browser Support

The numbers in the table specify the first browser version that fully supports Drag and Drop.

API
Drag and Drop 4.0 9.0 3.5 6.0 12.0

HTML Drag and Drop Example

The example below is a simple drag and drop example:

Example

<!DOCTYPE HTML>
<html>
<head>
<style>
#div1, #div2
{float:left; width:96px; height:55px; margin:10px 150px;padding:10px;border:1px solid #aaaaaa;}
</style>

<script>
function allowDrop(ev) {
    ev.preventDefault();
}

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

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> </div>

<img id="drag1" src="images/img_html201.gif" draggable="true"
ondragstart="drag(event)" width="96" height="55">

<div ondragover="allowDrop(event)" id="div2" ondrop="drop(event)"> </div>
</body>
</html>
Try it yourself »

It might seem complicated, but lets go through all the different parts of a drag and drop event.


Make an Element Draggable

First of all: To make an element draggable, set the draggable attribute to true:

<img draggable="true">

What to Drag - ondragstart and setdata()

...then, specify what should happen when the element is dragged.

In the example above, the ondragstart attribute calls a function, drag(event), that specifies what data to be dragged. the datatransfer.setdata() method sets the data type and the value of the dragged data:

function drag(ev) {
    ev.datatransfer.setdata("text", ev.target.id);
}

In this case, the data type is "text" and the value is the id of the draggable element ("drag1").


Where to Drop - ondragover

The ondragover event specifies where the dragged data can be dropped.

By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.

this is done by calling the event.preventdefault() method for the ondragover event:

event.preventdefault()

Do the Drop - ondrop

When the dragged data is dropped, a drop event occurs.

In the example above, the ondrop attribute calls a function, drop(event):

function drop(ev) {
    ev.preventdefault();
    var data = ev.datatransfer.getdata("text");
    ev.target.appendChild(document.getElementById(data));
}

Code explained:



 







HTML5 Local Storage


HTML local storage, better than cookies.


What is HTML Local Storage?

With local storage, web applications can store data locally within the user's browser.

Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.


Browser Support

The numbers in the table specify the first browser version that fully supports Local Storage.

API
Web Storage 4.0 8.0 3.5 4.0 11.5

HTML Local Storage Objects

HTML local storage provides two objects for storing data on the client:

Before using local storage, check browser support for localStorage and sessionStorage:

if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

The localStorage Object

The localStorage object stores the data with no expiration date. the data will not be deleted when the browser is closed, and will be available the next day, week, or year.

Example

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem ("lastname");
Not Available

Example explained:

The example above could also be written like this:

// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

The syntax for removing the "lastname" localStorage item is as follows:

localStorage.removeItem("lastname");

Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!

The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:

Example

if (localStorage.clickcount) {
    localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
    localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button" +
localStorage.clickcount + " time(s).";
Not Available

The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. the data is deleted when the user closes the specific browser tab.

The following example counts the number of times a user has clicked a button, in the current session:

Example

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Not Available