Link to home
Start Free TrialLog in
Avatar of nickmarshall
nickmarshall

asked on

localStorage problem

Hi,

I have a problem with accessing the localStorage values in my HTML5 application.

I am setting the localStorage key, groups at the top of my javascript file to an object as follows...

localStorage.setItem('groups', JSON.stringify(groups));

Open in new window


Within the document.ready part of my script I attempt to retrieve the value as follows...

function ShowList() {
    var groups = JSON.parse(localStorage.getItem('groups'));
    console.log(groups);
}

Open in new window


Inspecting the Firebug console shows, undefined for the log.  However, if I place an alert("HELLO") before groups is defined, the localStorage object is returned correctly...

function ShowList() {
    alert("HELLO");
    var groups = JSON.parse(localStorage.getItem('groups'));
    console.log(groups);
}

Open in new window


I think this may be to do with the DOM lifecycle, but can't figure it out.  

PLEASE HELP!!!
Avatar of devlab2012
devlab2012
Flag of India image

Do you have both the statements setItem and getItem in the same script file?

It might be the order in which you are using the javascript files. In general, localStorage is available in the document.ready and you may use it without any issue. Following is a simple HTML page, that uses the same code as listed by you:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="jquery-1.7.2.js"></script>
    <script language="javascript" type="text/javascript">

        var groups = "Test localStorage";
        localStorage.setItem('groups', JSON.stringify(groups));

        $( document ).ready(function() {
            //SaveList();
            ShowList();
        });

        function ShowList() {
            var groups = JSON.parse(localStorage.getItem('groups'));
            console.log(groups);
        }
    </script>
</head>

<body style="width:220px;">
This is HTML body.
</body>
</html>

Open in new window


NOTE: To test the above code, make sure that you correctly include the jquery file referenced in this code.
ASKER CERTIFIED SOLUTION
Avatar of nickmarshall
nickmarshall

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nickmarshall
nickmarshall

ASKER

Fixed myself.