Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable not accessible when initialized outside function

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?

like image 754
Nick Heiner Avatar asked Feb 18 '10 18:02

Nick Heiner


People also ask

Can I declare a variable outside function?

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

How do you access a variable from the outside function in Python?

To access a function variable outside the function without using "global" with Python, we can add an attribute to the function. to add the bye attribute to the hi function. We can do this since functions are objects in Python. And then we get the value with hi.

How do you access a variable in a function Python?

The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.


1 Answers

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.

like image 109
MLefrancois Avatar answered Oct 08 '22 11:10

MLefrancois