1

I am creating a website where when different functions occur in javaScript, I need to change the value of my local storage. For example here is my current code:

localStorage.setItem('colorvar', '#EBDBC2');

I need to create something where when a function occurs, the value which currently it set to #EBDBC2 will change to a value of my choice. I've tried just duplicating the line of code above and putting it in a function and changing the value but for some reason that wasn't working. Does anybody know how I can create a function where when the function runs, it will change the value in my local storage?

Aidan Young
  • 554
  • 4
  • 15
  • 3
    could you show how did you write the function? – miraj May 26 '21 at 21:06
  • 3
    Are you sure the function is running? Try adding a console.log to the function. – Bud Linville May 26 '21 at 21:08
  • Please see https://stackoverflow.com/help/how-to-ask, then revise your post with your attempt. Just asking for some code will surely get your question closed by the community. – isherwood May 26 '21 at 21:16
  • See [existing questions](https://stackoverflow.com/questions/58155249/how-to-change-the-value-of-an-item-in-localstorage-using-javascript) for assistance. – isherwood May 26 '21 at 21:21

1 Answers1

1

You can do it like this:

const setLocalStorageValue = (new_value) => localStorage.setItem('colorvar', new_value);
const getLocalStorageValue = () => localStorage.getItem('colorvar');

setLocalStorageValue('Value_1');
console.log(getLocalStorageValue());
setLocalStorageValue('Value_2');
console.log(getLocalStorageValue());

Here is the working example: https://jsfiddle.net/5af4e6ks/15/

NeNaD
  • 18,172
  • 8
  • 47
  • 89