skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. If the element with the class .active-box is dynamically moved to a different position in the DOM, the original click event listener attached to it will no longer work, because it is only associated with the original position of the element. Use event delegation: Attach the event listener to a parent element that is not moved, and then use the event.target property to determine if the clicked element matches the selector .active-box.

    document.addEventListener('click', function(event) {
      if (event.target.closest('.active-box')) {
        // Handle the click event on the .active-box element
      }
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search