user3267727
user3267727

Reputation: 35

HTML and Javascript Why must I perform all tasks in javascript inside functions that get called by the HTML?

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

Answers (2)

jfriend00
jfriend00

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:

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

  2. 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:

  • Doesn't use a global variables which is advantageous (variables are private to within the function and can't create conflicts with any other code or be interfered with by any other code).
  • The functionality is entirely contained within the function
  • There are no timing related issues with when the initialization code is run because the DOM is searched only when the operation is about to be carried out.
  • Getting DOM objects when needed works better with dynamically added HTML.
  • A simple user, triggered operation is plenty fast getting a DOM object when needed.

Upvotes: 0

Quentin
Quentin

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

Related Questions