The addEventListener
expects to receive a function in your second argument. However, note that you are calling for the function (before passing it to the addEventListener
). Behold "Calling Functions" in the documentation to learn more.
Because of this, instead of passing the function to the addEventListener
, you’re passing the return of the function you called. Since the function returns nothing, it is passing undefined
.
You need to pass the function reference (the name, for example):
var buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("mouseover", destacaButton, false);
}
function destacaButton() {
this.style.backgroundColor = "black";
}
Some modifications to the code:
- I transformed
black
in a string, like this: "black"
. Keep it the way it was (only the identifier black
) would probably cause a ReferenceError
.
- I changed the parameter
button
for this
. When the addEventListener
calls the function of callback, he associates the this
function to the element that caused the event. In this case, it will be the button itself.
A functional example:
var buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("mouseover", destacaButton, false);
}
function destacaButton() {
this.style.backgroundColor = "black";
}
<button>Botão 0</button> <button>Botão 1</button>
<button>Botão 2</button> <button>Botão 3</button>
<button>Botão 3</button> <button>Botão 5</button>
<button>Botão 6</button> <button>Botão 7</button>
<button>Botão 8</button> <button>Botão 9</button>
Caraca, perfect! I understood, perfectly. Thank you very much
– zepolik