The event
is a global variable window
and only gains properties within the Event Handler, like the addEventListener
.
The setTimeout
is a global function that does not assign to the variable event
the event properties, logo, event
isolated within the function of setTimeout
has no value whatsoever.
But first we need to know that it is always important to pass on the function of Event Handler the first parameter, representing the triggered event:
botao.addEventListener('click', (event) => {
↑
parâmetro
This is because less recent versions of browsers (such as Firefox) do not have the variable event
native, that is, the first console.log(event.target);
would already return the error event is not defined
, as explained in this other answer.
Therefore, when passing the event as a parameter of the addEventListener
it becomes a variable within the function and will have value also within the function of the setTimeout
:
const botao = document.querySelector('button');
botao.addEventListener('click', (event) => {
console.log(event.target);
setTimeout(function() {
console.log(event.target)
}, 500);
});
<button>Clique</button>
On the other hand, if you do not pass the event as a parameter of addEventListener
(which is not recommended, as explained above), you could submit the variable event
for the function of setTimeout
as follows, placing event
after the time of 500
:
const botao = document.querySelector('button');
botao.addEventListener('click', () => {
console.log(event.target);
setTimeout(function(event) {
console.log(event.target)
}, 500, event);
});
<button>Clique</button>
Try
this.event.target
– Pedro Roweder
Still returns as cannot get
target
of Undefined– Felipe Moreno Borges
Pq the Event within the
setTimeout
doesn’t mean anything there, has no connection to the button Event.– LeAndrade
addeventlistener('click', (Event) => {your code...}) Failed to set as callback parameter Event to use it.
– MauroAlmeida