There is a question with a good answer about binding multiple objects to a click event here, but the answer deals with only buttons inside a container. I am wondering what happens if there is a more complex structure, with elements inside the buttons and non-button elements inside the container. Will it still be more efficient to use a single eventhandler?
Consider this (not that complex) HTML:
<div id="container">
<div class="some nice red block"></div>
<div id="button_1" class="button">
<span>some text</span>
<img src="button_1_img.jpg">
</div>
<p>some more text</p>
<img src="a_nice_pic.png">
<div id="button_2" class="button">
<span>some text</span>
<img src="button_2_img.jpg">
</div>
<div id="button_3" class="button">
<span>some text</span>
<img src="button_3_img.jpg">
<div class="some icon"></div>
</div>
<p>some more text</p>
<img src="a_nice_pic.png">
//... more text, images and let's say up to 20 buttons
</div>
I could:
- Add eventlisteners to all buttons seperatly
- Add only one eventhandler to the container
In case 1 I need:
document.getElementById('button_1').addEventListener('click',dosomething,false);
document.getElementById('button_2').addEventListener('click',dosomething,false);
//etc... 18x
function dosomething(e){
var button=e.currentTarget.id;
//do something based on button id;
}
I then have 20 clickhandlers attached to 20 different buttons that only fire if the button is clicked.
In case 2 I need:
document.getElementById('container').addEventListener('click',dosomething,false);
function dosomething(e){
var container=e.currentTarget;
var clicked=e.target;
while(clicked != container){
if(clicked.className == 'button'){
var button=clicked.id;
//do something based on button id;
return;
}
else{
clicked=clicked.parentNode;
}
}
}
Now I have only one eventlistener. But it fires not only on the buttons, but on everything you click inside the container. And it has to travel up the DOM everytime to detect if there might be a button around the element clicked on.
So which one of the two is the most efficient in memory usage and performance? The one with more eventhandlers but less to do, or the one with only one eventhandler but more complex code?
I've made a fiddle to demonstrate the difference.
[edit] Perhaps I've oversimplified the example too much. There are moments some 200+ evenlisteners will be attached, in a maximum of 4 containers.