I'm trying to find the most productive way to hanging event.
Lets imagine we have this structure:
<ul>
<li> 1st li </li>
...
<li> 99999th li </li>
<ul>
So, we have about 10000 li elements and we want to add event listener to all this elements, lets say we can use jQuery too.
First thought
<li onclick="console.log(this)" >...</li>
bad part of this solution - we have increase a size of html markup because always repeating onlick.
Second thought
$('ul li').on('click', function(){
console.log(this)
})
Of course this solution is not an option because we add 10000 event listeners, obviously not good for performance.
Third thought, event delegation
$('ul').on('click', 'li', function(){
console.log(this)
})
looks really good as for me, we use only one event listener, not trashed html markup and it works as we need.
So, I asking this question, because sometimes I look at the source of different sites and big part of them use first way. Why? First way has some advantages?
I guess that maybe because it is easier to catch a dynamically added elements to the page, but may be there is something I do not know?
?
– Brian Jun 22 '13 at 21:07on the page :) what about a lot of different ul's for the various purposes on the same page, where you have to add own listeners to each of them?
– Denis Jun 24 '13 at 20:11