0

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"
        ] }
Metalois
  • 77
  • 1
  • 7
  • just shuffle your array, then pick them one by one in the comming order... – Mister Jojo Feb 18 '23 at 04:16
  • Do you know how to fetch data from the json file? – Metalois Feb 18 '23 at 04:43
  • 1
    yes, I know, and there must be thousands of answers here showing that. why this question ? – Mister Jojo Feb 18 '23 at 05:35
  • i did not find any that would fetch words from a json file, i might not know the exact keywords to search for since i lack some technical vocabulary. Since I could not find the answer to this, I gave up on the idea to use a json file, but I asked ChatGPT and he gave me a solution that worked with .js script. So the problem is solved now. – Metalois Feb 18 '23 at 13:55
  • Great !, I just hope that one day you will take the time to train yourself in technical concepts, to avoid becoming dependent on the goodwill of technologies. – Mister Jojo Feb 18 '23 at 14:02

0 Answers0