Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to add eventlistener to an element

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?

like image 634
Denis Avatar asked Dec 29 '25 03:12

Denis


2 Answers

I wouldn't look at "big sites" for the best web development practices. The first way has really no advantages over the other two, as it mixes JavaScript with HTML and is harder to maintain.

Event delegation will be lighter than the other two and will have the advantage of being able to handle dynamically generated elements, so in this case, it'd probably be the best choice. I would profile your application with both approaches before choosing.

like image 157
Blender Avatar answered Dec 30 '25 15:12

Blender


you can find your answer here- jQuery.click() vs onClick ,
As you can see http://jsperf.com/testper test, event delegation approach is the best approach for event hanging.In your case where you have 10000 or more events than surely 3rd approach is best for you.

like image 44
Anshul Avatar answered Dec 30 '25 15:12

Anshul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!