MozillaZine


JavaScript question: running a function inside a function

Discuss how to use and promote Web standards with the Mozilla Gecko engine.
Bethrezen
 
Posts: 411
Joined: September 13th, 2003, 11:56 am

Post Posted December 16th, 2021, 3:47 pm

Hi all

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>


My best guess as to what’s wrong is that I’m not calling the increment function correctly and this is conflicting with click event that I already have set on the outer function because if I move all the code inside the if statement outside of the outer function then everything works as expected.

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.

Return to Web Development / Standards Evangelism


Who is online

Users browsing this forum: No registered users and 2 guests