Showing posts with label HTML5. Show all posts
Showing posts with label HTML5. Show all posts

Thursday, June 26, 2014

How to check HTML5 Web Storage Support in JavaScript?

[caption id="attachment_879" align="alignnone" width="372"]HTML5 Data Storage HTML5 Data Storage[/caption]

[sourcecode language="javascript"]
function supports_html5_storage() {
                try {
                    return 'sessionStorage' in window && window['sessionStorage'] !== null;
                } catch (e) {
                    return false;
                }
            }
            alert(supports_html5_storage());
[/sourcecode]

Saturday, October 5, 2013

How to store an array in localStorage

This tutorial assumes that you are already familiar with HTML5  localStorage.

Although HTML5  localStorage is very useful, its usage is restricted to key value mechanism. Key and value is stored in string format despite what we need. For an instance, though you can specify a boolean type (either true or false) as the value, it is stored as a string.

What if we need to store multiple items as the value for a certain key. This can be little bit tricky if you gonna place an array directly as the value. When we scratch the surface of localStorage basic principles this is not possible. However you can come up with your own solutions that might work for you.

This tutorial demonstrates a simple way of handling above problem using json. We gonna store array as a json string. So nothing new here.

First add jQuery library as we are using some jQuery functions.

[sourcecode language="javascript"]
<script type="text/javascript">
var favorites_str = localStorage.getItem('my_favorites');
if(favorites_str == null) {
favorites = [];
favorites.push({ "name":"keshi", "id":"6" });
} else{
favorites = JSON.parse(favorites_str);
favorites.push({ "name":"sara", "id":"6" });

}
localStorage.setItem('my_favorites',JSON.stringify(favorites));
</script>

[/sourcecode]

To verify that above script is functioning please copy and run below script. It will make things easy, if you put this code in  a separate file.

[sourcecode language="javascript"]
<script type="text/javascript">
var data = localStorage.getItem('my_favorites');
if(data == null){
alert("0 favorites");
}else{
favorites = JSON.parse(data);
$.each(favorites, function(index,item){
alert(item.name);

});
}
</script>

[/sourcecode]

Sunday, August 11, 2013

HTML5 SQL Database Tutorial

[caption id="attachment_879" align="aligncenter" width="372"]HTML5 Data Storage HTML5 Data Storage[/caption]

HTML5 supports client side data storage. There are several types of storing data with HTML5

1. local storage through localStorage object

2. session storage through sessionStorage object

3. SQL based database

This tutorial demonstrates how to manage a client side SQL based database with HTML5.

Demo

[sourcecode language="html"]
<!DOCTYPE html>
<html>
<head>
<meta name=viewport content="user-scalable=no,width=device-width" />
<link rel="stylesheet" href="css/jquery.mobile-1.1.0.min.css" />
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.mobile-1.1.0.min.js"></script>
</head>
<body>
<div data-role=page id=home>
<div data-role=header>
<h1>Home</h1>
</div>

<div data-role="content">
<a href="#" data-role="button" id="create"> Create table </a>
<a href="#" data-role="button" id="remove"> Delete table </a>
<span> Item </span>
<input type="text" id="item">
<span> Quantity </span>
<input type="text" id="quantity">
<a href="#" data-role="button" id="insert">Insert item</a>
<a href="#" data-role="button" id="list">List items </a>

<ul data-inset="true" data-role="listview" id="itemlist"></ul>
</div>
</div>

<script>
var db = openDatabase ("itemDB", "1.0", "itemDB", 65535);
$("#create").bind ("click", function (e)
{
db.transaction (function (transaction)
{
var sql = "CREATE TABLE items " +
" (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"item VARCHAR(100) NOT NULL, " +
"quantity int(2) NOT NULL)"
transaction.executeSql (sql, undefined, function ()
{
alert ("Table created");
},error
);
});
});

$("#remove").bind ("click", function (e)
{
if (!confirm ("Delete table?", "")) return;;
db.transaction (function (transaction)
{
var sql = "DROP TABLE items";
transaction.executeSql (sql, undefined, success, error);
});
});

$("#insert").bind ("click", function (event)
{
var item = $("#item").val ();
var quantity = $("#quantity").val ();
db.transaction (function (transaction)
{
var sql = "INSERT INTO items (item, quantity) VALUES (?, ?)";
transaction.executeSql (sql, [item, quantity], function ()
{
alert ("Item created!");
}, error);
});
});

$("#list").bind ("click", function (event)
{
$("#itemlist").children().remove()
db.transaction (function (transaction)
{
var sql = "SELECT * FROM items";
transaction.executeSql (sql, undefined,
function (transaction, result)
{

if (result.rows.length)
{
for (var i = 0; i < result.rows.length; i++)
{
var row = result.rows.item (i);
var item = row.item;
var quantity = row.quantity;
$("#itemlist").append("<li>" + item + " - " + quantity + "</li>");
}
}
else
{
$("#itemlist").append("<li> No items </li>");
}
}, error);

});

});

function success ()
{
}

function error (transaction, err)
{
alert ("DB error : " + err.message);
return false;
}
</script>
</body>

</html>
[/sourcecode]

Please note that Firefox does not support this type of web SQL databases. If you try this in a FF browser, it will throw "ReferenceError: openDatabase is not defined".

Thursday, April 19, 2012

HTML5 Geolocation

Demo              Download

[sourcecode language="javascript"]
<!DOCTYPE html>
<html>
<head>

<script src="<a href="view-source:http://maps.googleapis.com/maps/api/js?sensor=false">http://maps.googleapis.com/maps/api/js?sensor=false</a>"></script>
<script>
// Integration with google maps
function loadMap(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);

var settings = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById('map_canvas'), settings);

var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Your Position!'
});

document.getElementById('status').innerHTML = 'Position Found!';
}

// Initialize geolocation
function initialize() {
if (navigator.geolocation) {
document.getElementById('status').innerHTML = 'Checking...';

navigator.geolocation.getCurrentPosition(
onSuccess,
onError, {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 120000
});
}
else {
document.getElementById('status').innerHTML = 'Geolocation not supported.';
}
}

// Map position retrieved successfully
function onSuccess(position) {
var data = '';

data += 'latitude: ' + position.coords.latitude + '<br/>';
data += 'longitude: ' + position.coords.longitude + '<br/>';
data += 'altitude: ' + position.coords.altitude + '<br/>';
data += 'accuracy: ' + position.coords.accuracy + '<br/>';
data += 'altitudeAccuracy: ' + position.coords.altitudeAccuracy + '<br/>';
data += 'heading: ' + position.coords.heading + '<br/>';
data += 'speed: ' + position.coords.speed + '<br/>';

document.getElementById('data').innerHTML = data;

loadMap(position.coords.latitude, position.coords.longitude);
}

// Error handler
function onError(err) {
var message;

switch (err.code) {
case 0:
message = 'Unknown error: ' + err.message;
break;
case 1:
message = 'You denied permission to retrieve a position.';
break;
case 2:
message = 'The browser was unable to determine a position: ' + error.message;
break;
case 3:
message = 'The browser timed out before retrieving the position.';
break;
}

document.getElementById('status').innerHTML = message;
}
</script>
</head>
<body onload="<a>initialize()</a>">
<div id="<a>status</a>"></div>
<div id="<a>data</a>"></div>
<div id="<a>map_canvas</a>" style="<a>width: 640px; height: 480px</a>"></div>
</body>
</html>

[/sourcecode]

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...