Variable not accessible when initialized outside function

Nick Heiner picture Nick Heiner · Feb 18, 2010 · Viewed 105.7k times · Source

When I use code like this, it works fine:

function removeWarning() {
    var systemStatus = document.getElementById("system-status");
    systemStatus.innerHTML = "";
}

function indicateInvalidUsername() {
    var systemStatus = document.getElementById("system-status");
    systemStatus.innerHTML = "Invalid username";
}

However, when I then want to move the systemStatus to be a global variable, it doesn't work:

var systemStatus = document.getElementById("system-status");

function removeWarning() {
    systemStatus.innerHTML = "";
}

function indicateInvalidUsername() {
    systemStatus.innerHTML = "Invalid username";
}

What am I supposed to be doing here?

Answer

MLefrancois picture MLefrancois · Feb 18, 2010

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

var systemStatus = document.getElementById("system-status");

is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.