DEV Community

Cover image for Day 9 : addEventListener('click', ..) and .onclick are not the same

Posted on

Day 9 : addEventListener('click', ..) and .onclick are not the same

so, this is different from previous posts. The past week was the first week of me posting any article on the web. Even after not writing everything in detailed form, the response I got was beyond my expectations. From now on, I will try my best to cover everything in detail..

addEventListener('click', ....) and .onclick are not the same

Yes, they are not the same. The difference being that in the addEventListener , we can add multiple listeners to the same event. While the onclick "overrides" the previous onclick attached to the same event.

For example:- see the below codepen

As a result, in the console:
When we click the onClick Button, only I’m also clicked! is logged out
When we click the addEventListner Button, both I’m clicked! and I’m also clicked! are logged out

To conclude, although we can attach the same event with different syntax, using addEventListener(‘click’, …) we can have multiple listeners on one event, whereas using onclick we can only assign one listener to one event (which is always the latest assigned listener).

Please open the above codepen through "edit in codepen" and then see the outputs in the console. I have added enough comments to make you understand everything. In case of any doubt, please do comment.

The full reference about the above point can be found at Medium.

Top comments (0)