0

My EventListener is calling the function before the click with this code... what's wrong with that line?

It was working fine when I had the function inside the parameter, but now that i'm calling it from there instead it's calling it prematurely before any click occurs.

divs[i].addEventListener('click', xopush(i), null);

It's calling a function with and argument passing to the function()... not an alert.

  • 1
    It should be `divs[i].addEventListener('click', xopush, null);` with no parens `()`. And the `, null` part should be either `true` or `false` (but this is not the problem). – ibrahim mahrir Dec 03 '17 at 05:22
  • I need it to pass that argument is why... – K. Jerry Alleyne Dec 03 '17 at 05:28
  • When you solve the above issue, and assuming by the looks of your code that you are using a loop, you'll end up having [**this very famous issue**](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – ibrahim mahrir Dec 03 '17 at 05:31
  • Then pass it as an anonymous function... `('click', function() { xopush(i); }, null)` – Tyler Roper Dec 03 '17 at 05:32
  • Yea, it's definitely within a loop. Solving one leads to a following issue because if I take out the argument it won't run the way I coded it to run in sequence. I'll have to get that argument passed otherwise. – K. Jerry Alleyne Dec 03 '17 at 05:33
  • It the same problem, in your case it's `xopush` and in the duplicate it's `alert`. Same way to fix too. – ibrahim mahrir Dec 03 '17 at 05:34
  • I hate to answer a dupe question so here is the answer in comment: `for(...) { (function(i) { divs[i].addEventListener('click', function() { xopush(i); }, false); })(i); }`. This should solve both problems. – ibrahim mahrir Dec 03 '17 at 05:37

1 Answers1

-1
//Instead of EventListener I usually prefer to use...

divs[i].onclick = function() {
    xopush(i);
}

... which is a answer to this. However, I was looking forward to using the eventListener so I could turn it off after 1 click on the element.

  • You can do the same using `addEventListener`. Please remove this answer. If you want to add something add it in the question, unless ofcourse, it is a valid answer that solves the problem. – ibrahim mahrir Dec 03 '17 at 05:41
  • Well, the onclick does solve this issue on its own. However, removing the addEventListener as the solution also removes the possibility of remove. – K. Jerry Alleyne Dec 03 '17 at 05:52
  • Your suggested solution for this actually creates the initial issue which led to this question. This anonymous function cannot be removed in the removeEventListener syntax. @ibrahimmahrir – K. Jerry Alleyne Dec 03 '17 at 06:08