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
});
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.
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.
onclick events run in the global scope and may cause unexpected error. performance and efficiency.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With