How to retrieve a JS variable list from another file?

Hello!

My GitHub page has a small segement of code that writes a random quote from a list:

var quotes = [
    "Quote 1",
    "Quote 2"
]
// Quotes was altered from the original for the sake of this example

var qrandom = Math.floor(Math.random() * (quotes.length));

function randomQuote()
{
      document.getElementById('quote').innerHTML = quotes[qrandom];
}

Now, could it be possible to grab the “var quotes list” from another JavaScript/JSON/etc. file? If so, how would the code exactly look like?

Thanks.

1 Like

If I understood your question correctly then my answer is…

Here are three files test.js, script.js and index.html

test.js

var qrandom = Math.floor(Math.random() * (quotes.length));

function randomQuote()
{
      document.getElementById('quote').innerHTML = quotes[qrandom];
}

randomQuote();

script.js

var quotes = [
    "Quote 1",
    "Quote 2"
]

and index.html

[blank file]

What you would do is add this code to the HTML page:

<script src="script.js"></script>
<script src="test.js"></script>

<div id="quote"></div>

Please tell me if I misunderstood your question.

That’ll work. Thank you.

1 Like