Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write random value from an array into paragraph element

I am trying to fetch the list of words from an external .txt file and put them into a javascript array, after which to pull a random word from that array and insert it into a paragraph element.

The words.txt:

"word1", "word2", "word3", "word4", "word5", "word6"

HTML and Javascript:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div><p id="word"></p></div>
<script>
         var wordList = fetch("/js/words.txt");
         var words = Array(wordList);
         const randomWord = Math.floor(Math.random()*words.length);
         function word() { document.getElementById("word").innerHTML = randomWord; }
</script>

When I load the webpage, it’s empty. There is no words in the paragraph element. What’s the issue?

>Solution :

The issue is that you’re not handling the asynchronous nature of the fetch function correctly. The fetch function returns a Promise that resolves to the response of the HTTP request. You need to handle this Promise and extract the text content from the response before you can use it.

you can do it like this:

`

 <div><p id="word"></p></div>
    <script>
        fetch('/js/words.txt")
            .then(response => response.text()) 
            .then(text => {

                var wordList = text.split(", ");                                
                const randomIndex = Math.floor(Math.random() * wordList.length);                
                const randomWord = wordList[randomIndex];
                
                document.getElementById("word").innerHTML = randomWord;
            })
            .catch(error => console.error('Error fetching words:', error));
    </script>

`

This code fetches the content of the "words.txt" file, splits it into an array of words using split(", "), generates a random index to pick a word from the array, and finally displays the random word in the paragraph element.

Make sure to adjust the file path "/js/words.txt" to the correct location of your "words.txt" file. Additionally, ensure that your server is configured to serve ".txt" files correctly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading