1

What is the difference between using addEventListener() in your Javascript code like this example:

Array.from(document.querySelectorAll('.element')).forEach(el => {
    el.addEventListener('ondrop', drop);
});

And calling the function directly in a HTML Tag?

<div class="element" ondrop="drop(event)"></div>
<div class="element" ondrop="drop(event)"></div>
<div class="element" ondrop="drop(event)"></div>
codedude
  • 6,244
  • 14
  • 63
  • 99

1 Answers1

2
  1. addEventListener can add multiple events, whereas with onclick this cannot be done.
  2. onclick can be added as an HTML attribute, whereas an addEventListener can only be added within <script> elements.
  3. addEventListener can take a third argument that can stop the event propagation.

Both can be used to handle events. However, addEventListener should be the preferred choice since it can do everything onclick does and more. Don't use inline onclick as HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.

iamdhavalparmar
  • 1,090
  • 6
  • 23