Home > OS >  How can I store a JavaScript variable in local storage?
How can I store a JavaScript variable in local storage?

Time:08-13

So I have a JavaScript variable called addNumber which just adds a number by 1 to a div any time I click a button. But I'm using it on a website which has multiple pages, and every time I change pages, it resets the counter. I've used console.log() to check the variable multiple times, and it always resets back to zero any time I leave the page, even when I keep the tab open. This counter is kept at the top of the page for all to see, and I want it kept there in a navbar, kind of like the shopping cart on Amazon. Is there a way I can do something like that using only vanilla JavaScript?

Thank you.

CodePudding user response:

You may find this link helpfull. https://www.w3schools.com/jsref/prop_win_localstorage.asp

Quick answer you store key value pairs using a string tag to identify them:

localStorage.setItem("lastname", "Smith");
localStorage.getItem("lastname"); //this returns the string "Smith"

Edit: i do not recommend you doing this in a production enviroment. You should stick to the framework of the project. If the project has no framework or is just for school or learning purposes then i guess is a viable option.

CodePudding user response:

You can store a variable in localStorage to access it somewhere else through

Try using:

function onClickevent(){
    addNumber = addNumber  1 
    localStorage.setItem('counter', addNumber);
}

Then get it through

//Just assign it to your div 
const getIt = localStorage.getItem('counter')

Here is some documentation on LocalStorage and how to use it :) https://www.w3schools.com/jsref/met_storage_getitem.asp

https://blog.logrocket.com/localstorage-javascript-complete-guide/#:~:text=To get items from localStorage, use the getItem() method,in the browser's localStorage object.

CodePudding user response:

The solution you can try is :

In the .js file at the end of all lines, type

window.localstorage.setItem("addNumber",addNumber);

The addNumber will be stored with an ID of addNumber.

To later retrieve, use :

window.localstorage.getItem("addNumber");

You may assign the above to a variable like

var number =....

Then console the number.

I hope this helps.

  • Related