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';
});
})();
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.