-1

I am trying to increase a counter each time a button get clicked.

Everything is working, except the increment (keep having "odd" as an alert).

gwd.auto_Unfold_tapareaAction = function(event) {

  var clickarea = document.getElementById('unfold_taparea');
  var elementClicked = 0;
  
  function handleIncrement() {
    elementClicked++;
  };
  
  clickarea.addEventListener('click', handleIncrement, true);
  if (elementClicked % 2 == 0) {
    alert("odd");
  } else {
    alert("even");
  };

};

If anyone knows how to do it, I'll be very grateful.

Thank you,

Loudvich.

  • 1
    The alert logic needs to be in the click function... The if else currently only runs when the script loads, it does not keep running. So you need to call it after you increment the number. Move that logic into the function and should probably do what you want. – epascarello Jul 26 '22 at 15:47
  • Epascarello, Thank you for your time. However, I've already tried it and it doesn't work like I'd like to. If if put the if/else inside of the function, the alert wouldn't notice when the first click is done. It would also stack the alerts each time I click and execute them in a row. For example, if this is the fifth time I click on the button, I would have 5 alerts. Do you know how to fix it ? – Louis Havet Jul 27 '22 at 07:16
  • Well that is how you would need to do it. You would need to debounce the alerts. https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript – epascarello Jul 27 '22 at 12:44

1 Answers1

0

Try placing the alert block inside the handleIncrement function at the end. My best guess is the alert block is not running after the counter is incremented.

Edit: it looks like this function is running every time some other element is clicked.

Your issue is that you are creating the new click listener every time the gwd.auto_Unfold_tapareaAction runs.

Since it's newly created every time, it increments once, then alerts.

Try running this whole block on load or something that only runs one time.

Ryan
  • 550
  • 4
  • 9
  • Ryan, Thank you for your time. However, I've already tried it and it doesn't work like I'd like to. If if put the if/else inside of the function, the alert wouldn't notice when the first click is done. It would also stack the alerts each time I click and execute them in a row. For example, if this is the fifth time I click on the button, I would have 5 alerts. Do you know how to fix it ? – Louis Havet Jul 27 '22 at 07:16
  • Every time this function runs, it adds another click listener. It looks like there are two separate items you are handling clicks for. – Ryan Jul 27 '22 at 16:38