The main difference is that with the onclick() you can only associate a function as callback of the event. Already with the addeventlistener() you can use as many functions as you want them to be activated when the event occurs.
Both are correct, but neither of them is "better" by itself, and there may be a reason for the developer to choose to use both approaches.
Example with the onclick (Only the second function):
let element = document.querySelector("#botao");
element.onclick = function() {
alert("Primeira função");
}
element.onclick = function() {
alert("Segunda função");
}
<button id="botao">Aperte</button>
Example with the addEventListenner (The first and second functions):
let element = document.querySelector("#botao");
element.addEventListener("click", function() {
alert("Primeira função");
});
element.addEventListener("click", function() {
alert("Segunda função");
});
<button id="botao">Apertar</button>
OBS: addeventlistener() does not work in versions prior to Internet Explorer 9. onclick() works in previous versions.
References:
- Alura
- Stackoverflow
I did not understand the negative. The explanation is correct.
– Augusto Vasques
I don’t understand it either. But I’m learning to respect and accept people’s voting choices. That’s why I get into the question of having to justify the upvote and the downvote. But anyway, this story has already yielded.
– Gato de Schrödinger
Pow, vlw for the answer, explanation I was needing. It helped a lot.
– Paulo Hainosz
Ball show, Paulo. May the strength be with you!
– Gato de Schrödinger
@Gambi this subject sucks. It’s probably a hater of yours. Imagine if he negative and leave as answer "I negative because I do not go with your face."
– Augusto Vasques
I must be awakening love in someone around here and I don’t know. Rs
– Gato de Schrödinger
... but the most important thing was to help the little boy there. That’s enough for me.
– Gato de Schrödinger