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?

4
  • 3
    could you show how did you write the function? Commented May 26, 2021 at 21:06
  • 3
    Are you sure the function is running? Try adding a console.log to the function. Commented May 26, 2021 at 21:08
  • Please see 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. Commented May 26, 2021 at 21:16
  • See existing questions for assistance. Commented May 26, 2021 at 21:21

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.