<...">

Is it more efficient to use addEventListener or onclick for performance?

I am using JavaScript only, no jQuery.

<div onclick="doFunction()"></div>
<div onclick="doFunction()"></div>
<div onclick="doFunction()"></div>
<div onclick="doFunction()"></div>
<div onclick="doFunction()"></div>
<div onclick="doFunction()"></div>

      

against

document.addEventListener('click', function () {
    //code here
});

      

+3


source to share


2 answers


addEventListner will be faster compared to onclick. You can check the below link for performance information by running tests.

http://jsperf.com/click-vs-addeventlistener/9



For more information on using them, you can check the following link.

addEventListener vs onclick

+4


source


  • By using "onclick" you are mixing Javascript and HTML, which is not considered good practice as it is not scalable. Consider adding, inserting, removing elements in your example dynamically. HTML describes structure, CSS describes styling, and JavaScript controls behavior.

  • If you haven't looked at Event Delegation : Event Delegation avoids adding event listeners to specific nodes, instead the eventlistener is added to a single parent.



Hence, addEventListener

with event delegation, there would be a way to go

+3


source







All Articles