0
Regarding global variables
Hello there! Iâm trying to make a basic webpage with a progress bar and a button that gives updates regarding the current status. However, I seem to be having issues when accessing variables (methods - they get the HTML element by ID) I stored at the beginning in the functions later (they give errors saying theyâre ânullâ), and this forces me to set the variables again as local variables in every function. What am I doing wrong? https://code.sololearn.com/W1dspZEP80Pt/?ref=app
5 Answers
+ 5
https://code.sololearn.com/WrZd10YRm3wB/?ref=app
See the execution order?
The code on the js section is executed before the body has loaded. Thus, the variable values are null.
Do
window.onload = () => {
//Do something...
}
Or alternatively, put the JavaScript in a script tag at the end of the body.
<body>
<!--Your code-->
<script>
// Do something...
</script>
</body>
+ 4
To set global variables, first declare them, then set them only when the page has loaded, otherwise you will be trying to get the HTML elements before they have loaded. Something like this:
var p, b, s, Pr;
window.onload = () => {
p = document.getElementById("bar");
b = document.getElementById("button");
s = document.getElementById("status");
Pr = setInterval (Progress, 100);
}
After this, you will not need to declare them again inside the functions.
+ 2
Code Crasher 3 alerts after document is loaded, so placing script in section 2 gives error in Android but not in ios, but section 3 doesn't give an error :)