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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With