So I just ran in to an odd little glitch, I’m trying to do an onclick counter and as far as I can tell my code should work correct however for some bizarre reason I don’t understand the counter will only increment once. Anyone have any idea what’s going on and why I can’t get this thing to work correctly?
Here is a striped down version of what I’m working on.
Code: Select all
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Tutorial</title>
</head>
<button type="button" id="counter">Counter</button>
<div id="count"></div>
<script>
var buttons = document.querySelectorAll("button");
for (i = 0; i < buttons.length; i++)
{
buttons[i].addEventListener("click", outer)
}
function outer(event)
{
var id = event.target.id;
if(id == "counter")
{
var counter = 0;
document.getElementById("count").innerHTML = counter;
function increment()
{
counter = counter + 1;
document.getElementById("count").innerHTML = counter;
}
document.getElementById("counter").onclick = increment;
}
}
</script>
</body>
</html>
So if I’m right about what’s wrong how then do I fix this because I have tried several different ways of calling the increment function and none of them work so clearly I’m missing something here.