Usually, in such tasks, one handler is used, this approach is called delegation ( delegation pattern ). The more listeners there are on the page, the more memory is wasted. If you have a more complicated option, then I recommend conducting an experiment and comparing methods using debugging tools.
Only you don’t need to check the coordinates, it’s enough to check the event.target
:
document.documentElement.addEventListener('click', function(event) { var target = event.target; switch (target.className) { // или тут может быть условие 'button': //... break; } });
If you are using jQuery , an example of this is the jQuery.on () method .
Still:
Regarding the cycle and anonymous function: if we create a new function in the cycle (that is, define it right there), then the memory will be spent on a bunch of functions created in the cycle. If this is required, then you should remove the function definition from the loop (so that it is one) and in the loop only refer to it, passing it in the parameter when adding an event.
A case in which delegation may not be as effective:
First, imagine a good situation for using delegation: there is an element catching clicks, there are elements on it that need to be caught right on it, without other elements nested in each other - everything is ok.
Now the reverse is the situation: there are a lot of nested elements, other elements have been added to your elements (which need to be caught), and also nested in each other. Now, if we click inside our element, we can get to a deep-lying child element. To find the parent we need, we will have to go to target.parentNode
in a loop from our element to the main event on which - this may be more expensive.