Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
How does event handler works in javascript?

the functions execution is done and wont ever be called again but still I can access the event handler inside it

(function () {
 const header = document.querySelector('h1');
 header.style.color = 'red';
 header.addEventListener('click', function () {
  this.style.color = this.style.color === 'blue' ? 'red' : 'blue';
 });
})();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In your JavaScript code, your are attaching an event handler to an object in the DOM.

Since the element doesn't disappear, after your IIFE ran, the handler is still attached to it, even though your header variable doesn't exist anymore.

document.querySelector("h1").click()
console.log("color after first click: " + document.querySelector("h1").style.color);

(function () {
 const header = document.querySelector('h1');
 header.style.color = 'red';
 header.addEventListener('click', function () {
  this.style.color = this.style.color === 'blue' ? 'red' : 'blue';
 });
})();

document.querySelector("h1").click()
console.log("color after second click: " + document.querySelector("h1").style.color)

document.querySelector("h1").click()
console.log("color after third click: " + document.querySelector("h1").style.color)
<h1>Test</h1>

You can see this even better if you attach the event listener via the onclick property, since event added via addEventListener can't easily be accessed afterwards:

console.log(document.querySelector("h1").onclick); // -> null

(function () {
 const header = document.querySelector('h1');
 header.style.color = 'red';
 header.onclick =  function () {
  this.style.color = this.style.color === 'blue' ? 'red' : 'blue';
 }
})();

document.querySelector("h1").click()

console.log(document.querySelector("h1").onclick) // -> your function
<h1>Test</h1>

If you want to remove an event listener from an element, you have to have a reference to the function you attached, otherwise the removeEventListener method will not work.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda