Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!