Timo Timo - 9 days ago 6
HTML Question

Import variables from another JavaScript file

Let's say I want to display all seasons of Family Guy as one number. (15)
But of course there will be more seasons so I would have to change in every file the 15 to 16 and so on.
That for I want to create a variable for the value so I just have to change it once for all files.

external js.script

var seasons = "15";
document.getElementById('seasons').innerHTML = seasons;


So now I want to include the variable in my HTML files:

<div id="seasons"></div>


It works but after three variables all other are not displayed.

Is there a better way to create variables in an external file?

Answer

If you need a group of constants within your application, it's usually a good idea to load them on to a namespace and load that in before any of your other code.

/* app.js */
// Create the namespace
var App = {};

App.Constants = {
  FAMILY_GUY: 15,
  SIMPSONS: 28,
  FUTURAMA: 7
};

/* family-guy.js */
document.getElementById('familyGuy').innerHTML = App.Constants.FAMILY_GUY;

/* simpsons.js */
document.getElementById('simpsons').innerHTML = App.Constants.SIMPSONS;

/* futurama.js */
document.getElementById('futurama').innerHTML = App.Constants.FUTURAMA;
<div id="familyGuy"></div>
<div id="simpsons"></div>
<div id="futurama"></div>

<!-- 
Imagine you're loading your files like this
<script src="app.js"></script>
<script src="family-guy.js"></script>
<script src="simpsons.js"></script>
<script src="futurama.js"></script>
-->