Storing Data on the Client

HTML5 offers two new objects for storing data on the client:

  • localStorage – stores data with no time limit
  • sessionStorage – stores data for one session

Earlier, this was done with cookies. Cookies are not suitable for large amounts of data, because they are passed on by EVERY request to the server, making it very slow and in-effective.

In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website’s performance.

The data is stored in different areas for different websites, and a website can only access data stored by itself.

HTML5 uses JavaScript to store and access the data.


The localStorage Object

The localStorage object stores the data with no time limit. The data will be available the next day, week, or year.

How to create and access a localStorage:

Example

<script type=”text/javascript”>
localStorage.lastname=”Smith”;
document.write(localStorage.lastname);
</script>

Try it yourself »

The following example counts the number of times a user has visited a page:

Example

<script type=”text/javascript”>
if (localStorage.pagecount)
{
localStorage.pagecount=Number(localStorage.pagecount) +1;
}
else
{
localStorage.pagecount=1;
}
document.write(“Visits “+ localStorage.pagecount + ” time(s).”);
</script>

Try it yourself »

 


The sessionStorage Object

The sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window.

How to create and access a sessionStorage:

Example

<script type=”text/javascript”>
sessionStorage.lastname=”Smith”;
document.write(sessionStorage.lastname);
</script>

Try it yourself »

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

Example

<script type=”text/javascript”>
if (sessionStorage.pagecount)
{
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else
{
sessionStorage.pagecount=1;
}
document.write(“Visits “+sessionStorage.pagecount+” time(s) this session.”);
</script>

Try it yourself »

Source from http://www.w3schools.com

HTML5 Geolocation

HTML5 Geolocation is used to locate a user’s position


Locate the User’s Position

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

Internet Explorer Firefox Opera Google Chrome Safari

Internet Explorer 9, Firefox, Chrome, Safari and Opera support Geolocation.

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


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

Try it yourself »

Example explained:

  • Check if Geolocation is supported
  • If supported, run the getCurrentPosition() method. If not, display a message to the user
  • If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter ( showPosition )
  • The showPosition() function gets the displays the Latitude and Longitude

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

Try it yourself »

Error Codes:

  • Permission denied – The user did not allow Geolocation
  • Position unavailable – It is not possible to get the current location
  •  Timeout – The operation timed out

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=400×300&sensor=false”;

document.getElementById(“mapholder”).innerHTML=”<img src=’”+img_url+”‘ />”;
}

Try it yourself »

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

Google Map Script
How to use a script to 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:

  • Up-to-date local information
  • Showing Points-of-interest near the user
  • Turn-by-turn navigation (GPS)

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>

Try it yourself »

Source from http://www.w3schools.com

HTML5 Canvas

The canvas element is used to draw graphics on a web page.

Your browser does not support the canvas element.


What is Canvas?

The HTML5 canvas element uses JavaScript to draw graphics on a web page.

A canvas is a rectangular area, and you control every pixel of it.

The canvas element has several methods for drawing paths, boxes, circles, characters, and adding images.


Create a Canvas Element

Add a canvas element to the HTML5 page.

Specify the id, width, and height of the element:

<canvas id=”myCanvas” width=”200″ height=”100″></canvas>

 


Draw With JavaScript

The canvas element has no drawing abilities of its own. All drawing must be done inside a JavaScript:

<script type=”text/javascript”>
var c=document.getElementById(“myCanvas”);
var ctx=c.getContext(“2d”);
ctx.fillStyle=”#FF0000″;
ctx.fillRect(0,0,150,75);
</script>

Try it yourself »

JavaScript uses the id to find the canvas element:

var c=document.getElementById(“myCanvas”);

Then, create a context object:

var ctx=c.getContext(“2d”);

The getContext(“2d”) object is a built-in HTML5 object, with many methods to draw paths, boxes, circles, characters, images and more.

The next two lines draws a red rectangle:

ctx.fillStyle=”#FF0000″;
ctx.fillRect(0,0,150,75);

The fillStyle method makes it red, and the fillRect method specifies the shape, position, and size.


Understanding Coordinates

The fillRect method above had the parameters (0,0,150,75).

This means: Draw a 150×75 rectangle on the canvas, starting at the top left corner (0,0).

The canvas’ X and Y coordinates are used to position drawings on the canvas.

Mouse over the rectangle below to see the coordinates:

X
Y

More Canvas Examples

Below are more examples of drawing on the canvas element:

Example – Line

Draw a line by specifying where to start, and where to stop:

Your browser does not support the canvas element.

Try it yourself »

 

Example – Circle

Draw a circle by specifying the size, color, and position:

Your browser does not support the canvas element.

Try it yourself »

 

Example – Gradient

Draw a gradient background with the colors you specify:

Your browser does not support the canvas element.

Try it yourself »

 

Example – Image

Put an image on the canvas:

Try it yourself »

 


HTML5 <canvas> Tag

Tag Description
<canvas> Defines graphics

 

Complete Canvas 2d Reference

For a complete reference of all the attributes and methods that can be used with the canvas object, go to our complete canvas 2d reference.

Source from http://www.w3schools.com

HTML5 Drag and Drop

Drag and drop is a part of the HTML5 standard.


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

Internet Explorer Firefox Opera Google Chrome Safari

Internet Explorer 9, Firefox, Chrome, and Safari 5 support drag and drop.

Note: Drag and drop does not work in Safari 5.1.2.


Drag and Drop Example

The example below is a simple drag and drop example:

Example

<!DOCTYPE HTML>
<html>
<head>
<script type=”text/javascript”>
function allowDrop(ev)
{
ev.preventDefault();
}function drag(ev)
{
ev.dataTransfer.setData(“Text”,ev.target.id);
}

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

<div id=”div1″ ondrop=”drop(event)”
ondragover=”allowDrop(event)”></div>
<img id=”drag1″ src=”img_logo.gif” draggable=”true”
ondragstart=”drag(event)” width=”336″ height=”69″ />

</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)
{
var data=ev.dataTransfer.getData(“Text”);
ev.target.appendChild(document.getElementById(data));
ev.preventDefault();
}

Code explained:

  • Get the dragged data with the dataTransfer.getData(“Text”) method. This method will return any data that was set to the same type in the setData() method
  • The dragged data is the id of the dragged element (“drag1″)
  • Append the dragged element into the drop element
  • Call preventDefault() to prevent the browser default handling of the data
    (default is open as link on drop)

Source from http://www.w3schools.com

HTML5 Audio

HTML5 provides a standard for playing audio files.


Audio on the Web

Until now, there has not been a standard for playing audio files on a web page.

Today, most audio files are played through a plug-in (like flash). However, different browsers may have different plug-ins.

HTML5 defines a new element which specifies a standard way to embed an audio file on a web page: the <audio> element.


How It Works

To play an audio file in HTML5, this is all you need:

Example

<audio controls=”controls”>
<source src=”song.ogg” type=”audio/ogg” />
<source src=”song.mp3″ type=”audio/mpeg” />
Your browser does not support the audio element.
</audio>

Try it yourself »

The control attribute adds audio controls, like play, pause, and volume.

You should also insert text content between the <audio> and </audio> tags for browsers that do not support the <audio> element.

The <audio> element allows multiple <source> elements. <source> elements can link to different audio files. The browser will use the first recognized format.


Audio Formats and Browser Support

Currently, there are 3 supported file formats for the <audio> element: MP3, Wav, and Ogg:

Browser MP3 Wav Ogg
Internet Explorer 9 YES NO NO
Firefox 4.0 NO YES YES
Google Chrome 6 YES YES YES
Apple Safari 5 YES YES NO
Opera 10.6 NO YES YES

 


HTML5 audio Tags

Tag Description
<audio> Defines sound content
<source> Defines multiple media resources for media elements, such as <video> and <audio>

Source from http://www.w3schools.com

Ping your blog, website, or RSS feed for Free Sitetag