I'm trying to create a page with a button that when clicked, it returns a random word from a list.
I have a list of over 300 words, in a text file. each word is in a new line. I was able to convert that list into a json array. Since I have so many words, I want to avoid writing all of them inside the .js script, and instead fetch them from json file.
Been searching for an answer but all results are not quite what I need. I currently have this and it's not working:
const subButton = document.getElementById('generate-word');
const resultBox = document.getElementById('result-box');
let words = [];
// Fetch the words from the JSON file
fetch('words.json')
.then(response => response.json())
.then(data => {
words = data;
});
// Add an event listener to the button
subButton.addEventListener('click', () => {
// Generate a random index to select a random word
const randomIndex = Math.floor(Math.random() * words.length);
// Get the selected word
const selectedWord = words[randomIndex].word;
// Remove the selected word from the array
words.splice(randomIndex, 1);
})
<div>
<button id="generate-word">Generate!</button>
<div id="result-box"></div>
</div>
<script src="words.js"></script>
Json file: words.json
{ "words": [
"apple",
"banana",
"orange",
"coconut",
"cantaloupe",
"shoe"
] }