0

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?

2
  • 1
    What do you mean "but after three variables all other are not displayed"? The number of variables shouldn't change the functionality here. Commented Dec 1, 2016 at 19:00
  • I am having the same issue, the first three variables will display, but then I get an error: "Cannot set property 'innerHTML' of null" even though it worked for the first three (my variables are identical at this stage). Commented Apr 8, 2017 at 4:10

1 Answer 1

2

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>
-->

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! But is there another way than creating lots of little js script files?
@Timo You can make as many or as few files as you want. That's all up to you. Theoretically you could write all of this in one file. This shows you how to create a global variable, App, that holds your constants rather than individual variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.