can addEventListener be dynamically called?

Advertisements

I need clarity, Whether addEventListener be dynamically called on DOM element which gets updated.
enter image description here

domelemet1 is fired on event click, then in that event function call it gets updated to random DOM element, now whether the past DOM only gets fired or the updated DOM gets fired? I checked that past DOM gets fired, I just need Clarification.

>Solution :

When you do:

domElement1.addEventListener(/*...*/);

you’re adding an event listener to the DOM element that the domElement1 variable refers to, not to the variable itself. There’s no ongoing connection between the variable and the event listener. You can assign a different value to the variable, or even let the element go out of scope and cease to exist:

function handler() {
    console.log("Clicked!");
}

function example() {
    // This variable ceases to exist once this function returns
    const btn = document.querySelector("input[type=button]");
    btn.addEventListener("click", handler);
}

example();
<input type="button" value="Click Me">

The variables you use to refer to DOM elements aren’t the actual elements, they’re just a means of interacting with the elements.


In a comment on the question you asked:

Suppose lets say, there are two boxes ( box1 and box2 ), box1 has class active-Box , I called Event trigger on active-Box and that event shift the active-Box class to Box2 from BOX1. so, now box2 has active-box class and removed from box1. upto here everything is okay, as event gets triggered on active-box click and box2 has active-box class, now which box gets triggered ? Box1 or Box2 ?

What matters is what element you attached the event handler to. If you attached it to Box1, then it’s attached to Box1. It doesn’t matter whether you change what classes Box1 has, and or what you do with Box2. It doesn’t matter how you got your reference to Box1. For instance, if you got it by doing document.querySelector(".some-class"), it doesn’t matter whether the element still has that class later. The class was only used to find the element at that moment in time.

Leave a ReplyCancel reply