TJ15
TJ15

Reputation: 363

Saving multiple values using HTML5 local Storage

I have a page that utilises local storage to hold the amount of times a button is clicked:

function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (localStorage.clickcount) {
            localStorage.clickcount = Number(localStorage.clickcount)+1;
        } else {
            localStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "" + localStorage.clickcount + ".";
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
}

I now want to add 3 more buttons and want to store the values for each of these separately. To display it I know I would refer to the appropriate ID but I'm not sure how to store these values. I imagine that I will have 3 further functions that will perform this and need to create a variable for each of the values? Am i on the correct path?

Upvotes: 0

Views: 704

Answers (2)

Akshay Arora
Akshay Arora

Reputation: 1945

In short, you can do the following to store items in localStorage:

localStorage.firstButtonCount += 1;

localStorage.secondButtonCount +=1;

The crux of the matter is that localStorage behaves like a javascript object. So, it means you should keep in mind that if you use . dot notation to do this, you cannot do it for keys that come from a variable and are determined at runtime. Use square bracket notation [] for such a case.

var my = 'firstButtonCount';
var second = 'secondButtonCount';

if(something > 10){
localStorage[my] += 1; // Determined dynamically
} else{
localStorage[second] += 1; 
}

Upvotes: 3

Clark Ozanne
Clark Ozanne

Reputation: 96

You can continue to use dot notation to add new items to your localStorage object. localStorage.keyName = value is totally acceptable. To see what it looks like open your browser dev tools and enter localStorage in the console. You will see that it is basically just an object.

Upvotes: 0

Related Questions