I read the following:
"if users can interact with a lot of elements on a page, adding event listeners to each element can use a lot of memory and slow down performance...
...because events affecting containing elements you can place event handlers on a containing element and use the event target property to find out which of its children the event occured on"
So, what are the downsides to just doing one click event on the body and then delegating the correct function?
I have an example here: http://jsfiddle.net/jkg0h99d/3/
Code backup for deadlink:
HTML:
<div id="test" class="box">gfdgsfdg </div>
<div id="test2" class="box">gfdsgfdsg</div>
<div id="test3" class="box">fdsgfdsgg</div>
<ul id="test4" class="box">
<li id="test5" class="box">fsgfdsg</li>
<li id="test6" class="box">gfdsgfds</li>
<li id="test7" class="box">gfdsgfds</li>
<li id="test8" class="box">gfdsgfds</li>
</ul>
JS:
var body = document.body;
if (body.addEventListener) {
body.addEventListener('click', function (e) {
delegate(e, "click");
}, false);
} else {
body.attachEvent('onclick', function (e) {
delegate(e, "click");
}, false);
}
function delegate(e) {
var sourceNode = e.target || e.srcElement;
var id = sourceNode.id;
switch (id) {
case ("test"):
// do some func
break;
case ("test2"):
// do some func
break;
case ("test3"):
// do some func
break;
case ("test4"):
// do some func
break;
default:
// do nothing
break;
}
}
Interesting point: It will raise an event every time a user clicks. But, is that really going to be a problem? All it does is check through a switch (or could be if checks)
The point of this is mere interest, however a user has asked about the point optimisation. I am thinking this could very quickly be optimised further but I will keep the discussion on topic.