Reputation: 35
It keeps me from easily defining global variables and its often a nuisance. Why doesn't the code outside functions that are called execute? For example, if I call the function myFunction from HTML, this works...
function myFunction() {
var myObject = document.getElementById("myHTMLObject");
myObject.style.backgroundColor = "blue";
}
but not this...
var myObject = document.getElementById("myHTMLObject");
function myFunction() {
myObject.style.backgroundColor = "blue";
}
If I call the function from the HTML, only the code inside that function will run (unless that function calls other functions). Am I making a mistake or is there a way around this? I don't want to encompass all my code in a window.onload function.
P.S. I run my html on Chrome if it makes a difference.
Thanks for any help.
Upvotes: 0
Views: 58
Reputation: 708056
If this example:
var myObject = document.getElementById("myHTMLObject");
function myFunction() {
myObject.style.backgroundColor = "blue";
}
doesn't work, then here are a couple possible reasons:
The script is running too early and thus when you do document.getElementById("myHTMLObject");
, the page has not yet been loaded and thus myHTMLObject
does not exist yet.
You have more than one global definition of myObject
and one is overwriting the other.
Your second coding example is recommended for a number of reasons:
Upvotes: 0
Reputation: 944432
It does execute, and does when when the script runs, which is when the <script>
element is parsed.
If you try to get an element that is added to the DOM by HTML that appears after the <script>
, then it won't exist when you look for it so you will get nothing back.
If the <script>
appears after the element, then you won't have a problem.
Upvotes: 1