Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using JavaScript only, without 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>

vs

document.addEventListener('click', function () {
    //code here
});
like image 679
geoyws Avatar asked Sep 24 '14 03:09

geoyws


People also ask

Is it better to use onclick or addEventListener?

Summary: addEventListener can add multiple events, whereas with onclick this cannot be done. onclick can be added as an HTML attribute, whereas an addEventListener can only be added within <script> elements.

What is the benefit of the addEventListener () method?

The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

Why is using onclick () in HTML a bad practice?

onclick events run in the global scope and may cause unexpected error. performance and efficiency.

Is Onclick an event handler?

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app.


1 Answers

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

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

For more details on using those, you can check the following link.

addEventListener vs onclick

like image 98
Kalyan Avatar answered Sep 20 '22 20:09

Kalyan