Oct 062013
CSS Animation

CSS3 is great way to Create Animations, we can replace flash Animations,Animated images and JavaScript with CSS3 Animation properties.

In this CSS3 Animation Tutorial I will explain how to create Walking Man Animation Effect Using CSS3 alone as shown below.

CSS3 Animation

CSS3 Animation Tutorial


At the end of this post you will understand following CSS3 Animation Properties.

  • CSS3 KeyFrame Animation :        property which allows us to create animations.
  • CSS3 Transform :                              property which allows us to rotate,scale,skew,move elements.
  • CSS3 Transform Origin :                property which sets the origin of transformations

First we will create static man here is the sample HTML code


We divided man into two parts

  • Man Body which contains Head , chest and Hands.
  • Man Legs

Now we will apply CSS


The CSS code is straight forward except transform property(For Middle Part)

  • Skew property turns element at an given angle,depending upon parameters X or Y axis


In our example I used skewY which turns element vertically(Y-axis) -30 deg.

  • And scale property increased or decreases the element size, depending on the parameters given for the width (X-axis) and the height (Y-axis)

The above code creates sample body parts as shown below

CSS3 Animation

CSS3 Animation Tutorial


Now we have to align all this body parts to create man

Apply the following CSS Code.


This will create the static Man as shown below.

CSS Animation

CSS3 Animation Tutorial

Now we apply CSS3 KeyFrame rule  property to move this man.

What is CSS3 KeyFrame rule?

This property allows us to Create Animations Using CSS3. Keyframe property supports all major browsers (IE 10+) and for safari chrome we have to prefix corresponding browser engine

To create Animations follow below two steps

  • First Define CSS styles inside the @keyframetag
  • Now apply the rule to the element using animation property.

Observe the below sample CSS3 KeyFrame Animation Example which changes the div color to red to yellow for every 5 sec


We defined a @keyframe with name “myfirst”  We are changing from red to yellow.And applying the animation property on div with duration. You must specify the duration otherwise animation wont effect because default value is ‘0’

We can use keywords like “from” and “to” for changing styles or we can specify change in percent 0% means “first”  and 100% means “to”

0% is the beginning of the animation and 100% is when the animation is complete. Visit W3schools for more details.

Now come to our CSS3 Animation Demo

I divided animations into two parts

  • Moving hands and Legs
  • Moving Entire Body

For Moving Hands Apply the Following CSS


Right hand and left leg should sink with each other so applied same CSS3 Animation Effect for both elements and vice versa.

For moving hands I am using CSS3 transform rotate property from 30 degrees to -30 degree.

And I applied CSS3 transform-origin property as 0%(x-axis) 0%(Y-axis) which specify that with respect to element starting position we should apply the transformation.

i.e., we should rotate leg or hand at angle of 30 deg with respect element starting position.(Remove this property in demo example and check the animation you will understand in a better way).

And infinite means continuously we should apply the animation.

Here is the CSS3 Animation.

Animation Using CSS3

Animation Using CSS3

Only Legs and Hands are moving rite. Now we should move entire body for that purpose I applied following animation to manBody


The Logic straight forward simply we should apply the margin-left style  30px to 600px for every 9 sec.

Here is the Final Demo for Walking Man Effect Using CSS3 Animation.

NOTE: The above CSS is for Chrome and Safari which uses Webkit engine For Opera and IE10 No need to add any prefix and For mozilla add Moz prefix.

The Demo works fine with Chrome Safari Mozilla IE10 I have not tested with Opera I hope it will work.

Also Read: Google Hangout Effects using HTML5 Canvas

I hope you’ve enjoyed this CSS3 Animation Tutorial and that it gives you more ideas on CSS3 Animation effects.If so share this post with your friends and also join our mailing list I will be sharing my learnings and experiments with HTML5 and CSS3

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me.

And Finally Don’t Forgot to Join Our Reader List. Read Popular tutorial on HTML5

Sep 242013

Today I will explain How to create a Simple Collapsing  Header Using CSS with an Example.

Here is the demo  Collapsing Header CSS

Now a days most of the webpages are contains Header and  Banner.

So First We will divide page into three parts like Header,Banner and Content.

Here is the sample HTML




You might be thinking what is this header tag, The header tag is new in HTML5. It supports almost all browsers. Here is the quick round of introduction to header Tag.

  • The <header> tag represents a header for a document or section
  • The <header> element should be used as a container for introductory content or set of navigational links.
  • You can have multiple <header> elements in one document.

The following CSS code will apply to Header Element


Height I given as 100px and positions as fixed to prevent the scrolling.The important thing here is Z-Index of header it should have higher index

  • Height I given as 100px
  • Positions as fixed to prevent the scrolling.
  • The important thing here is Z-Index of header should have higher index.this will ensure the rest of the page that does flows underneath  the header. So I gave some maximum value as 10.

And Next thing is Banner

  • This needs scrolling effect.
  • As I given header height as 100px. It should be fixed relative to header height so I given position as fixed and top 100px.
  • This will ensure banner content to sit directly underneath the header.

And Finally Content

  • We given header as 100px and Banner as 300px so relatively content should start from 400 px from top
  • So I gave position as relative and top as 400px.

Here is the Finale Demo Simple Collapsing Header using CSS

I prefer you to read this awesome book on CSS  CSS3: The Missing Manual

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me.

And Finally Don’t Forgot to Join Our Reader List.


Sep 152013
Google Effects

Google hangouts very popular because of Google effects like face masks and background effects.

I tried to implement Google Effects using HTML5 Canvas,HTML5 getUserMedia API via javaScript face detection library by  Liuliu.

To simplify I divided this tutorial into two parts First getUserMedia basics and Second Face detection & Google Effects.

Please go through the getUserMedia basics then you will understand the logic clearly.

Continuous to previous post, we learnt how to take snapshot using getUsermedia and Canvas. Here is the Demo


Just remove capture button and replace onclick event with setInterval Method as shown below


The Logic is simple I am injecting local media stream video into HTML5 Canvas.For every 30msec one latest image snapshot will be drawn on canvas. As the Time Interval is very less both video and canvas look like exactly same. Here is the Demo.

Now we will understand face detection JavaScript by LiuLiu. The library contains two js file ccv.js and face.js.

 Go to the A Not-so-slow JavaScript Face Detector, upload your image it takes some time and then an Orange color circle will be drawn on image.here is the sample demo

Face Detection Using javascript

Face Detection Using javascript

It took almost 1537ms to detect the faces.The Library is capable of detection multiple faces. I have gone through the page source actually it’s HTML5 canvas element.
  •  First Image is drawn in Canvas.
  • And then the library has one method ccv.detect_objects() which takes canvas(which contains image) element as argument and it returns array of  coordinates of faces.
  • Finally looping through the coordinates,drawing circle on canvas using context.arc method.

The code behind is


Also Read : basics of LocalStorage API

Detect_objecta take so many arguments like cascade,interval,min_neighbours I don’t know about these arguments I have not explored much about it.I am using this detech_objects alone to detect face.

I modified the snapshot method as shown below


The Logic here is

  • whenever snapshot called a new image drawn onto the canvas.
  • I am passing that canvas to detect_objects method it will return coordinates of faces.
  • And I increase interval time to 800 because detect_objects taking 1500ms to detect the face coordinates.
  • And Finally instead of drawing circle on our face we will draw Mask Image(I am using three images batman mask and Glasses with Mask,PirateCaptain).

I modified HTML as shown below


I created two buttons with Id’s GlassesWithMask and Batman which are two effects in our Google Effects Web App. Onclick we are calling selectMask method. And the Javascript is

  • I declared one variable MaskImage of type Image()
  • In selectmask() method I am assigning MaskImage with id of button.
  • And in Snapshot() method I am replacing ctx.arc with ctx.drawImage as explained above.
  • In the snapshot method I am drawing MaksImage on each face (based on selected mask you have add or substract positions the mentioned metrix will works for most of the Masks)
  • If two people are in Webcam they will be masked with selected feature.
  • I am adding “.png” at the end. i.e., id of buttons and Images should be same so that onclick we can easily change the MaskImage
  • Refer below Image The Mentioned Images are our two Google Effects.


I Added some CSS code to style our Google Effects page.Here is the Final HTML Code.


Here is the Final Google Effects Demo.

You have to enable getUserMedia in your browser. That I explained in previous post If you have any queries feel free to comment.

Remember getUserMedia does’not work on file:// URL you have host html in IIS or Apache.Use Chrome or Mozilla or Opera


It’s not perfect. Keep Your Face straight and Close to Webcam(with Clean Background) and Remove your Eye Glasses if you have.

And Your suggestions are always welcome Please Add your valuable feedback to improve this App.



I prefer you to read this awesome book on Canvas
Core HTML5 Canvas: Graphics, Animation, and Game Development (Core Series)

I hope you’ve enjoyed this article and that it gives you more ideas face detection and getUserMedia API.If so share this post with your friends and also join our mailing list I will be sharing my learning’s and experiments with HTML5

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me.

And Finally Don’t Forgot to Join Our Reader List. Read Popular tutorial on HTML5

Sep 152013
HTML5 getUserMedia Demo

In this tutorial I will explain how to capture video and audio using getUserMedia  in HTML5 with an example.Then I will explain how to take snapshot using HTML5 getUserMedia API.

And Finally You will learn how to implement Google Hangout Effects using html5 getUserMedia API

First take a look at browser support for javascript getUserMedia API.

HTML5 getUserMedia browser support:

Currently chrome,mozilla,opera supports getUsermedia API.

For chrome and Mozilla we have to prefix corresponding web engine i.e., for chrome we have to use “webkitGetUserMedia” function and for mozilla “mozGetUserMedia” function.

For Opera no need to add any prefix simply use “getUserMedia”.

By default getUserMedia disabled in chrome and mozilla.

To enable getUserMedia in Chrome type ‘chrome://flags/’ in URL bar and enable “Enable screen capture support in getUserMedia(). Mac, Windows, Linux, Chrome OS” option.

To enable getUserMedia in Mozilla type ‘about:config’ in URL bar search for “media.navigator.enabled” and set it True.

Safari and InternetExplorer does not support getUserMedia.

For more information check getUserMedia Browser Support

getUserMedia Example:

One important thing you should remember is

You cannot use getUserMedia on web pages served using file:// URLs.

So host your HTML file in Apache or IIS , then browse better use Visual Studio.

Here is the sample HTML file


And next we will write javascript code. Instead of if else loops to support different browser we will define navigator.getUserMedia as shown below.


Now we will understand HTML5 getUserMedia function it will take three arguments like constraints,successCallback,FailureCallback. The syntax is shown below.


getUserMedia constraints are nothing but which media streams to use i.e., audio or video.And it is required field


successcallback is the function we call when media stream is loaded successfully in our case put it into video tag.success callback is required field.

The getUserMedia function will call the function specified in the successCallback with the LocalMediaStream object that contains the media stream.

  • First we are getting video element using document.querySelector()
  • And Then creating a object URL for the localMediaStream provided by the getUserMedia using window.URL.createObjectURL
  • Finally use this URL for the source of Video element.


Failure callback is the function we call when media stream cannot be loaded.The function called with different types of code arguments as mentioned below.And it is optional however in mozilla it’s required field.

PERMISSION_DENIEDThe user denied permission to use a media device required for the operation.
NOT_SUPPORTED_ERRORA constraint specified is not supported by the browser.
MANDATORY_UNSATISFIED_ERRORNo media tracks of the type specified in the constraints are found.


Sample errorCallback function


err.name will display the corresponding error codes

And here is the Final Code. Load your document (remember host it on apache or IIS) and grant permission.


And Next step we will take snapshot and display it into HTML5 Canvas element.

Add Canvas tag and Capture Button to our HTML Code.


And then add javaScript code


I added snapshot() method

  • Canvas width and height we are assigning to video element width and height
  • And then We are drawing Image on canvas using drawImage() function which takes argument video element and X,Y Coordinate position.
  • And Finally we added this method to capture button click event.
HTML5 getUserMedia Demo

HTML5 getUserMedia Demo

Here is the Final Demo.

Actually I tried to implement Google Hangout effects using HTML5 Canvas and getUserMedia, so in this post I tried to cover all basics of  HTML5 getUserMedia.

Go through this awesome article  Learn how to implement Google Hangout effects

Google Effects

Google Effects


I prefer you to read this awesome book on Canvas
Core HTML5 Canvas: Graphics, Animation, and Game Development (Core Series)

I hope you’ve enjoyed this article and that it gives you more ideas on HTML5 getUserMedia API .If so share this post with your friends and also join our mailing list I will be sharing my learnings and experiments with HTML5

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me.

And Finally Don’t Forgot to Join Our Reader List. Read Popular tutorial on HTML5


Sep 082013
Matrix Effect

Now a days I am playing around with HTML5 Canvas API and Java Script. It’s an amazing option to create animations.

This weekend I saw The Matrix movie.This film known for it’s visual effect.

Then I thought is it possible to Create Matrix effects using HTML5 and JavaScript   something like below.

Matrix Effect

Matrix Effect

First I wrote some JavaScript code as mentioned below.


I wrote one Matrix function In which I am filling canvas with “Matrix” word at random locations using Canvas fillText method(Line 10). And I am calling that function using Javascript setInterval Method (Line  12)(Interval Time 30.)

Line 7 and 8 will fill the screen with background color black and opacity of 0.05.

When each time the Matrix function is called,Canvas fillStyle will draw the background on the screen.Because of this you can see text has different colors at different places on canvas.Some text will have green color without transparent background color. This is because there will be a new layer drawn on the screen each time the Matrix is called

Line 10 will draw “Matrix” word at random locations. I am using JavaScript Math.random() to do the same. Here is the Simple Matrix Effect Demo.

But this is not what we expected,Carefully observe the above Matrix Effect Gif Image: All alphabets are drawn along Y-Axis while X-Coordinates are constant.So I changed my code little bit as shown below.This is the key point in our Algorithm to Create Matrix effect using HTML5


Algorithm Behind Matrix Effects using HTML5 Canvas And JavaScript:

Here I declared an array (YPositions) to store Y-Coordinates.Initially array will contain all zero’s.And Inside draw() function I am using Java script Array Map function, basically It Creates a new array with the results of calling a provided function on every element in this array.

Here is the quick Example of Java Script Array Map


The Array index starts at ‘0’ zero so, For X -co ordinate I am adding 10,Our X coordinates are (10,20,30,40………290)(Line 12)

And Y co-ordinates will vary from (0 to 110) If  Y value > 100 I am resetting array element to ‘0’ otherwise incrementing 10.(Line 14 to 21). Here I am not using new Array I am changing existing(YPositions) array itself using Java Script Array Map function.

I am drawing ‘a’ character on canvas at (x,y) locations. (Line 13).

  • i.e., on first Iteration we will draw “a” at (10,10)(20,10)(30,10)……(290,10)
  • Second Iteration  (10,20)(20,20)(30,20)……….(290,20) and this goes until Y >100 then we will reset the value to ‘0’

Also Read   :  Simple Algorithm to Draw Polygon using HTML5 Canvas

I think now you understood the Logic behind this implementation if you are still in doubt refer below image.



I think now your clear with Logic.

Now we have to replace “a” with random alphabets and Y positions to some random coordinates to create actual Matrix Effect using HTML5 and javaScript  Here is the final Code.


I am using Java script String Char from Code Method(Line 27) to generate random alphabets which take ASCII Value as input and gives corresponding character. In short it will convert ASCII Codes to Characters.

And also I added two buttons to Play and Pause Matrix Effects. I prefer you to read Simple Snake Game using HTML5 Canvas to understand this buttons mechanism.

Here is the Final demo of Matrix effects using HTML5 and JavaScript

Learn how to implement  Google Hangout webcam Effects using HTML5 getUserMedia 

I prefer you to read this awesome book on Canvas
Core HTML5 Canvas: Graphics, Animation, and Game Development (Core Series)

I hope you’ve enjoyed this article and that it gives you more ideas on how we can implement animations using the HTML5 Canvas API.If so share this post with your friends and also join our mailing list I will be sharing my learnings and experiments with HTML5

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me.

And Finally Don’t Forgot to Join Our Reader List. Read Popular tutorial on HTML5

Aug 282013
HTML5 Canvas Polygon

How to Draw Polygons using Html5 canvas?

First we have to identify the points on HTML5 canvas and then use context.lineto() method for drawing lines and finally use stroke or fill method to make polygon visible. Here is the sample code for Drawing HTML5 Canvas Polygon

Html5 canvas API comes with so many options and we can draw anything using Javascript  based upon path abstractions.


But the problem is how identify the points to draw polygon?

In this post I will explain how to draw a regular polygon using HTML5 Canvas. 

And also pattern to identify the points to draw polygon.

What exactly this regular polygon is.In a regular polygon all angles and all sides are equal.

HTML5 Canvas Polygon

HTML5 Canvas Polygon

If we observe the above images we can come to know that all vertices of regular polygon can be located on a circle.In other words regular polygon can be inscribed within a circle.

Also read: How to develop simple snake game using HTML5 cavas

We will go to our school days and understands some trigonometry functions cosine sine etc. Any point in a circle can be identified as  (r cos e,r sin e) where r is the radius and e is the angle.Refer below images. This is the key point in our algorithm to draw regular  HTML5 Canvas Polygon.



For instance we will take equilateral triangle,as explained above this triangle divides circle into three equal parts and each part will make an angle of 120 degrees at the center(360/3=120).

Now identify the three vertices

  • First vertex     : at 0 degree i.e., (r cos 0,r sin 0)=(r,0)
  • Second vertx  : at 120 degree i.e., (r cos 120,r sin 120)
  • Third vertex    : at 240 degree i.e., (r cos 240,r sin 240)


Now our algorithm is ready.

  • First take number of sides(n) and radius of circle(r)
  • And calculate angle made by the each side of regular polygon at center (360/n)
  • Identify the first vertex (r,0)
  • Loop through the angles to identify the points
  • And draw the polygon using store or fill method

Observe the below code carefully I will explain each line one by one.


We are passing context(ctx),center of regular polygon(x,y),radius(r),number of sides(sides) as parameter to regular polygon function.if sides < 3 we cannot make a polygon so return directly.

Next angle calculation,HTML5 canvas and Javascript trigonometric functions will take radian  as unit to specify angles rather than degrees.And 2*,Math.PI(Javascript notation for PI) is equal to 360 degrees.

Now moving the center to (x,y) using translate method.

Next We will move to the first point of regular polygon using moveTo() method that is nothing but (r,0) as explained above.

Loop through the sides to identify remaining two points and then close the path using closePath() .

Draw Triangle using HTML5 Canvas:-

However this function will not draw anything just it will define drawing path and we have to use storke or fill method to make polygon visible. Here is the sample HTML5 Code.


This will draw the triangle exactly as shown in above figure (with radius (3,0)) But that is not visually straight because we made first point as (3,0)

To make triangle straight we have to rotate the context about 90 degrees(negative direction i.e., -Math.PI/2) so we will slightly change our method as shown below


And now below code will draw exactly straight triangle


If you don’t want to rotate the triangle do not pass the last argument i.e., rotateAngle.

I hope you understand  how to draw a regular polygon using HTML5 canvas.

But how we can generalize these to any polygon simply follow the below steps.For instance a take pentagon which is not regular pentagon

  •  Identify any five points on a circle.
  • To identify the points we have to divide 360 degrees into 5 parts which are not equal(Say 80,90,100,30,60 degrees)
  • These angles are nothing but angles made by the each side at center of circle.
  • Now we know the points draw the lines using LineTo and finally stroke it. Please look into the below code.

Draw Polygon using HTML5 Canvas:-


For regular polygons all angles are equal so we took a for loop to identify the points but this is not the case for normal polygon so we have to add angles one by one to identify the points.

The above code looks somewhat tricky, But I feel this is the best way to identify the points of a polygon on HTML5 Canvas instead of giving points normally like c.lineTo(120,50) where we have to guess so many points to Draw HTML5 Canvas Polygon.

Live Demo For HTML5 Canvas Polygon

I prefer you to read this awesome book on Canvas
Core HTML5 Canvas: Graphics, Animation, and Game Development (Core Series)

I hope you’ve enjoyed this article and that it gives you more ideas on how you can use the HTML5 Canvas API.If so join our mailing list I will be sharing my learnings and experiments with HTML5

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me

And Finally Don’t Forgot to Join Our Reader List.

Oct 222012

I will explain basics of HTML5 Canvas with an Example.

You will learn How to develop Snake Game using HTML5 Canvas.If you familiar with JQuery then it’s very easy.

HTML5 Code:

These are the main elements in html.

  • One <canvas> element for Snake Game.
  • Two <audio> tags for GamePlay and GameOver
  • One <p> Tag for displaying Scores.
  • And buttons for Play,pause,SoundOFF,SoundON.

Game Conditions:

  • Use Arrows to Move Snake.
  • And exit Game when snake eat itself.It’s your decision you can exit your game if it hits the Wall.

Now Play around with Jquery:

First thing Logic of the Game.It is simple.

  • Create an Array of Snake.
  • Write a function to paint snake array in Canvas.
  • Write a function for creating food.
  • Moving of snake:Remove Tail of the snake(Last element in array) and append to the Head(First Element)
  • Increment the Head.
  • Trigger the Paint function continuously.
  • And write exit conditions.


Key Board Movements:

Here is the code for key board movements. This function calls when keydown event occurs.Here I am checking one condition “allowPressKeys” this will disable the arrows when game is in pause mode.


Creating Food and snake:

Creating food is nothing but painting one random pixel within the canvas.Each time generate one random pixel,paint it.For Snake Declare one array.Assign some length initially.Call Paint_cell function.


Checking Exit Conditions:

If snake head meets it’s body then the game will end. Ouroboros_Check take arguments HeadX,HeadY,And SnakeArray,checks whether head meets Snake Body.(The Ouroboros is a symbol representing a Dragan eating own it’s tail.).When game ends we will call Startgame function.


Play and Pause Game:

The key of the Game is calling Paint function continuously.  setInterval is a standard Java Script function,we can call it with a function(or code snippet) to execute it for every period in milliseconds.

For Example  var AlertMsg=setInterval(function (){alert(“Hello”);},2000);

The above Code  display alert message for every 2 seconds. And For stopping we use clearInterval(AlertMsg) function.

In play method we will call setInterval with Paint() and in Pause we will call clearInterval.


Game Sounds And Buttons:

With <audio> tag in HTML5 We can include sounds in Web page.I am used three audio tags for Gameplaying(background music),GameOver(When snake eat itself) and SnakeEatingFood.


And I included some text between <audio> and <canvas> tags.

If a browser supports canvas and audio tags then it simply ignore the text between the tags.And If not then the browser ignore the tags and displays the text between tags.No need to check canvas and audio support explicitly.


Click here to Play Game now.Turn On Your Speakers,Use Arrows to Move Snake,Use buttons for play pause and sound OFF ON.

If you have any doubts,suggestion feel Free to Post comments.

Download Source Code

Oct 102012

In my earlier post I explained basic concepts of Local Storage API.If you are new it’s better to refer Understanding Local Storage API in HTML5.

Before writing web pages in html5 you need to think about two things.

  • Browser compatibility:- You can check browser compatibility using html5test.com. Right now Chrome is leading with 437points(out of 500) and next Maxthon,Opera,Safari,Mozilla and finally as you expected IE9 with 137points.IE 10 is under development which supports html5 features up to 319points.
  • What if the browser wont support? some of the browsers wont support new html5 features in that case we need to provide meaningful alternative.
  • And check whether feature is supported by browser or not for web storage you can use window[“localstorage”]
But the good news is that all the browsers(even the mobile browser you can check all these details in html5test.com) are moving towards the HTML5 standards.And HTML5 is not declared as standard by W3c right now(Expected to be stable standard by 2014) May be w3c will come up with proper solution to support the older browser(it’s depends on how fast users upgrading their browser).


Now I will explain how to use Web Storage API to save user preferences in client browser especially in eCommerce sites.Usually most of the eCommerce sites save user search preferences using cookies.When the user loads page for the next time browser will send cookie along with http request and displays the search preferences.But we can use web storage Api to do the same effectively (without much complexity).


Multi Search using Web Storage API:
This is the Sample HTML file for Multi Search functionality.
  • One text box for entering search items
  • One button for adding search items to local storage as well as DOM
  • One button for clearing local storage and DOM elements
  • And one list for showing search items.



JavaScript Code:-


The following are the main functions in Java Script
  • Adding search items to LocalStorage
  • Adding search items to DOM
  • Getting existing Search Item list from local storage.
  • Deleting search Items.
Adding search Item to Local Storage:-
 Local storage api is all about key/value pairs.Creating unique keys are the main important thing in this Local storage.Here I am using Date function to create unique keys.First I am creating unique items and then I am pushing those items into another array ‘searchItemsArray’.To access items easily.As the Local storage supports only string format Iam using JSON.stringify() to convert array to string and save it into localStorage, and JSON.parse() to parse string to array.


Getting existing search items from localstorage:-
After adding key into localstorage we need to get existing searchItemsArray,If searchItemsArray not existing (i.e., if we are loading page first time) we are creating an array and adding it into local storage else we are getting existing ‘searchItemsArray’


Adding search items to DOM:-
And finally we are reading each element in ‘searchItemsArray’ and adding it into DOM.


Deleting the search Items:-
And I added one button for clear all search Items and also if the user clicks on single element I am clearing that element using onClick method on ‘li’ element.




Oct 062012
Html5 Local Storage

In this Tutorial I will explain all the Basics of HTML5 Local Storage API.

It’s often referred as Web Storage. Web storage is nothing but client side storage.Right now we are using cookies for the purpose of storing objects locally in client machine(in browser).

There is a big debate happening around cookie vs Local Storage I don’t want to get into that but I will start with Cookie basics, limitations of cookies and then Html5 Local Storage

Why Cookie?

Cookies are mainly used in Shopping carts to customize the user experience by storing data locally(user specific).I will explain how cookie works in high level.

  • Your playing a game in online,to maintain your state of game server will store cookies in your browser.
  • If you close the browser and try to access the same website then browser will send cookie along with HTTP request.
  • Based on Cookie,server customize the user experience and retrieve the state of a game
  • And Cookies are Domain Specific i.e., abc.com cannot access cookie of xyz.com.
Cookie is nothing but Key Value pair stored in a browser.

Limitations of Cookies :-

  • Cookies can able to store only 4k of data. For each domain browser will assign 4k of memory.
  • Each time browser has to send cookie along with HTTP request,it’s inefficient especially if you are using mobile device with not a lot of bandwidth
  • Difficult to handle(I mean coding) cookie key value pairs within a HTTP request.
  • Each time we are sending cookie along with http request,Are we sending our personal data?
  • Finally everything is handle at server side,there is no client side development.

Introduction to HTML5 Local Storage:-

In HTML5 there is no concept of Cookies everything can be done by Local Storage API.A simple JavaScript API in the browser for storing Key value pairs that are persistent and you are not limited to 4k of memory.

Html5 Local Storage

Html5 Local Storage

HTML5 Local Storage browser support:

Almost All browsers are supports HTML5 Local storage. I checked the Local storage API browser compatibility  in HTML5test.com Here is the  result   click here.

Internet explorer 6,7 ,Opera 10 ,Firefox 3.0 are not supporting this HTML5 local storage API anyway we are not using these browsers now a days

HTML5 Local Storage limit:

All browsers today offering 5-10 MB of storage in every user’s browser.i.e., For each domain 5MB of local storage.

HTML5 local storage supports different web apps and mobile apps.Local storage is nothing but your app can store data in browser to reduce communication needed with the server.

A page can store one or more key/value pairs in the browser’s local storage.And later use key to retrieve value. These can be done by Local Storage object in local storage API.

You may thing why Local Storage why not Web Storage,Web refers to something more and we are implementing at client side,local make sense instead of Web.

Html5 Local Storage Example:-

Before going to example first we will understand basic functions of html5 local storage. With “localstorage” object we can create a key using ‘setItem‘ method.And to retrieve value use ‘getItem‘ method.


Most of the browsers support local storage object but safer side you can check browser compatibility as shown below


And also keys are unique for example 


Now value contain value2 not value1. And one thing Local Storage stores only string values.But in Shopping cart if we want to store item counts and prices in Local Storage you need to use parsing.


Html5 Local Storage Array:-

Instead of using setItem and getItem methods we can use arrays as shown below


And Local Storage has two interesting things :Length property and Key method.Length property holds number of items in the local store.And get can be used to retrieve value as shown below

for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage[key];

or you can use foreach loop as shown below

for (var key in localStorage) {
var value = localStorage[key];alert(value); }

And you can remove keys from Local Storage using removeItem method: localStorage.removeItem(key);

Html5 Session Storage:-

If you substitute the global variable sessionStorage everywhere you’ve used localStorage then your items are stored only during the browser session. So, as soon as that session is over (in other words, the user closes the browser window), the items in storage are removed.The sessionStorage object supports exactly the same API as Local Storage.

Where we can see Local Storage keys and Values:-

LocalStorageinChromeAnd we can see the local storage key values in browsers using developer tools as shown in the pic.In developer tools select resources and Local Storage. you can select key and delete from browser itself instead of using local storage removeItem method.

To clear entire local storage you can use


But how to use this clear method you need to create one sample HTML page.No need to bother download this ClearWebStorage.html file and click on clear button it will clear the total localStorage elements.


What happens if 5MB storage exceeds:-

If 5MB storage exceeds browser should throw QUOTA_EXCEEDED_ERR exception.Most of the modern browsers will throw this exception.And remember don’t forgot to use try,catch loops.If you are not using it may crash the browser if it exceeds 5mb storage.Do you want to test this? download this BlowUpStorage.html file and test.

Important things to be remember while using Local Storage API:-

  • There is no naming conventions available for HTML5 LocalStorage keys,but those should be unique.
  • The problem here is,For example you have one domain say abc.com it has two applications or two pages Page1 and Page2 Page1 can access localstorage items set by page2 and vice versa, because those two pages are under the same domain.So you need to select naming scheme for your local storage that won’t conflict with other applications at the same domain.
  • And if you want to store arrays or objects into local storage use JSON.stringify to store the value and JSON.parse to retrive the value.
For naming you can follow a simple procedure for example if you have two apps in your domain,assign one unique appid for each app and then use that appId to create local storage keys as shown below.
Html5 Local storage Naming Convenstions

Html5 Local storage Naming Convenstions

Is HTML5 Local Storage can replace Cookies?

We can do everything with Local Storage api in HTML5 that can be done using cookies,but it cannot be the end of cookies ,because we are using cookies from long back and Most of the websites are still depending upon cookies,

Imagine webpages without cookies?

How many developers willing to change their codes?

This is my personal opinion if you have any concerns feel free to post comments.

And in my next post I will try to explain Local Storage in HTML5 with an example.

I hope you understood the basics of HTML5 Local Storage API in this Tutorial. Now go through the next post to learn how to use Local Storage API HTML5 LocalStorageStorage example.

Thanks for Reading my Post. Please Take a look around My blog,Keep up to date with my Posts..
Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me

And Finally Don’t Forgot to Join Our Reader List.

You might Like

Beginning Html5

A new era in web development

Html5 canvas tutorial

Aug 252012
 Tim Berners lee introduced HTML and wrote Browser in early 1990’s. The main purpose is to use and share documents among CERN researchers. 
After that it is continuously adding many new features like CSS, Java Script etc..
More than two decades after HTML was introduced still we are asking questions about Web like
What is World Wide Web?
What it can be?
What are the main features and applications we can use and really important to us?
What are the tools available to develop these great sites and apps? And Finally
How effectively we can build these apps and sites so that it can fit into Browser?
These questions led to the new era of Web Development HTML5 , latest version of HTML.
the future is landing
A new era of Web Development
Lot of discussions going around the world on HTML5 like
HTML5 is all about multimedia, getting rid of plug-ins and  support for audio and video.
It’s about rich Internet clients. Instead of building clients with plug-ins like Flash, now we can use canvas, transforms and JavaScript to build cool web pages and animations.
HTML5 will supports client-side storage and caching functionality .or we can say Offline access to the web?
And also Mobile apps..!
So What exactly it is?
HTML5 is all these things. It’s a family of technologies that can be used to built web pages and application.
HTML5 working
What Does HTML5 Do?
 Its is going to change the Web in coming years..
 Watch this space for HTML5 tutorials and notes..
Optimization WordPress Plugins & Solutions by W3 EDGE