My task is to create an HTML button that displays different messages on the page depending on the number of times the button is pressed. My code below contains one global variable (counter) to count the number of times the button is pressed. The code works, but I've read that you should avoid global variables.
var counter = 0; // global variable
window.onload = function() {
document.getElementById("button").onclick = go;
}
function go() {
counter++
switch(counter) {
case 1:
document.getElementById("output").textContent = "You pushed the button.";
break;
case 2:
document.getElementById("output").textContent = "You pushed the button (again).";
break;
case 3:
case 4:
case 5:
document.getElementById("output").textContent = "You pushed the button "
+ counter.toString() + " times.";
break;
default:
document.getElementById("output").textContent = "Stop pushing the button."
}
}
I read Define global variable in a JavaScript function which said to wrap the function (go
in my case) in a "scoping function" with the global variable directly inside that, like so:
window.onload = function() {
document.getElementById("button").onclick = go;
}
(function() {
var counter = 0; // Global now inside the scoping function
function go() {
counter++
switch(counter) {
case 1:
document.getElementById("output").textContent = "You pushed the button.";
break;
case 2:
document.getElementById("output").textContent = "You pushed the button (again).";
break;
case 3:
case 4:
case 5:
document.getElementById("output").textContent = "You pushed the button "
+ counter.toString() + " times.";
break;
default:
document.getElementById("output").textContent = "Stop pushing the button."
}
}
})();
but when I tried that my code didn't work at all. Any suggestions?
window.onload
was misleading. – yroc Oct 14 '15 at 16:25