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
});
source to share
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.
source to share
-
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
source to share