I have a web application where I am trying to store different images, ( which are there across different pages, ) in an ImageArray
which is a javascript array. I looked up the net and found that LocalStorage API
in HTML5 is an effective way to do this, since the variables are preserved even after page reload.
My problem is I have an ImageArray
in which I am storing my images by using the saveImage()
function.
var ImageArray = new Array(); //declared as global variables
var i=0; //declared as global variables
function saveImages(Image)
{
if(ImageArray.length < 4)
{
ImageArray[i] = new Image();
ImageArray[i].src = Image;
//alert('ImageArray:::'+ ImageArray);
// ImageArray.push(Image);
i=i+1;
alert('Added For Comparison : ');
alert('no_of_pics_added' + ImageArray.length);
window.localStorage.setItem('ImageArray', JSON.stringify(ImageArray));
//alert('ImageArray' + JSON.stringify(ImageArray))
}
else
{
alert('You have already added 4 pics for comparison' + ImageArray.length);
}
}
and this is the displayImages()
function which is supposed to retrieve the saved images.
function displayImages()
{
if(window.localStorage.getItem('ImageArray') == null){
alert('12124235246');
var ImageArray =[];
}
else
{ alert('98987987');
ImageArray = JSON.parse(window.localStorage.getItem('ImageArray'));
}
ImageArray = new Array(); // initialising once the Images are displayed
i=0;
}
The program goes into the else loop but nothing happens. I figure out from this that window.localStorage.getItem
and the window.localStorage.setItem functions are the problem here. I have tried using both window.localStorage.getItem
and localStorage.getItem
. I am using a browser which supports HTML5
(chrome 37).
I have been refering these links
How to get JS variable to retain value after page refresh?
How to retain javascript array while page refresh?
Somebody please tell me what I am doing wrong. Thanks in advance.:)