Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda