0

trying to build a quick game. Whereby the word appears at the top of the page, the users click on the correct antonym. I'm trying to add functionality so the users can add their own word pairs. For example:

var iWords = ['new','tall','hot'];
var btn = document.getElementById('btn');

btn.addListenerEvent('click', function() {
var newWord = prompt('What word do you want to add?');
iWords.push(newWord);
});

The code works perfectly, other than when the page refreshes it initalizes iWords from the global var.

Is there any way to permanently push the added words in?

Many thanks, Tom

2

2 Answers 2

1

The localStorage and sessionStorage properties allow to save key/value pairs in a web browser.

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

1 Comment

Keep in mind that local storage is not forever, and isnt a replacement for a real database.
0

There are multiple approaches to tackle this. You could store in localStorage, use cookies or store on server side (in some DB).

Here's an example with localStorage:


// define iWords array & initialize it as empty array.
let iWords = [];

// Check if any existing iWords exists in local storage
const dataInLocalStorage = localStorage.getItem('iWords');
if (dataInLocalStorage !== null) {
    iWords = JSON.parse(dataInLocalStorage);
} else {
  // otherwise initialize iWords with some values.
  iWords = ['new', 'tall', 'hot'];
}


var btn = document.getElementById('btn');

btn.addListenerEvent('click', function () {
  var newWord = prompt('What word do you want to add?');
  iWords.push(newWord);
  // now here, whenever user enters a new word, store & update in localStorage
  // when the page will be refreshed, this stored value will be extracted 
  // from localStorage and assigned to iWords
  localStorage.setItem('iWords', JSON.stringify(iWords));
});


The caveat here is that this is still a temporary storage in browser and won't be stored forever. Storing on server side could be better option, depending on your use case.

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.