Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I don't know what the proper terminology is for this, but I have a piece of code with a list of items here.


HTML
<motto><center><span id="motto">Loading MOTD...</span></motto>



<script>
const months = ["Hi, I'm Paul!",
"February",
"It is time to rise."];





const random = Math.floor(Math.random() * months.length);
var motd=(months[random]);
document.getElementById("motto").innerHTML=motd;
</script>


I'd like the list to be in a separate file, rather than being part of the code itself. How can I do this?

What I have tried:

I don't really know where to start with this, as I'm very new to javascript and coding in general.
Posted
Updated 22-Feb-23 23:16pm

You can store data in .json files and deploy them with your application, then load the data Using the Fetch API - Web APIs | MDN[^]

This allows you to make a background request to load a resource from a provided path or URL, then deserialize the content. You could store your month values as JSON, in the format:
JSON
["January", "February", "March", ..]

Then simply load the data. Here's an example JSFiddle which loads an array of monarchs[^] from a public JSON file. By calling the await fetch() the JS will return a response, and then further calling await response.json() we then convert the fetched data into a JSON object.

Just remember that if you're testing from a simple .html file in your browser, the browser may not allow access to files on the file system. In those cases you'd probably need to deploy the HTML and JS files as part of a webserver (ie. Node)
 
Share this answer
 
Comments
Andre Oosthuizen 23-Feb-23 5:21am    
Straight forward and in detail, my 5
Chris Copeland 23-Feb-23 5:28am    
Thanks :)
you have to use your file as external resource by :
<script src="the_file_path.ext"></script>


the file content must be :
var the_list = [item,item,item,item,,,,,...]" ;

remenber it's JS file in this example, that why the var is JS typed with 'var' name= [];.
 
Share this answer
 
v3
Comments
Chris Copeland 23-Feb-23 5:32am    
For OP's benefit, here is a good page describing the difference between 'var' and 'let'/'const'[^] just so there's no confusion. var would be required in this solution's suggestion to make it globally available, while let and const should be used in most cases.
Member 15627495 23-Feb-23 8:14am    
to add a comment about JS vars :
'var' the_var; // it's for 'global' Var, through 'all JS scope' reachable. 
'--->void' the_var ; // for 'local scope', not reachable from other JS scope.

'let' the_var ; // coming in JS with 'lambda expression' , for 'local scope' use. modern JS
const the_var ; // constant Var

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900