javascriptevent-handlingdom-eventsevent-delegation

How can I delegate 'change' event on input element from body?


I know already about event delegation by jQuery. However, How can I do same thing with pure Javascript without jQuery.

Although I attached change event on body or the top element(div), change event is not triggered when value of input element in body or top element is changed...

How can I do this?


Solution

  • Tl;DR: you probably need to listen on the input event instead.


    The reason you are probably not seeing the event being triggered, is because it is triggered: "...when the element loses focus after its value was changed." Source: MDN.

    What you probably need to listen to, is the input event instead which "fires when the value has been changed." Source: MDN

    Here's an event listener attached to the <body> HTML element which captures all the 'bubbled' input and change events (see how the input event is triggered immediately whereas the change event requires that the input element loses focus, e.g. when pressing Tab):

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Input Event Delegation</title>
      </head>
      <body>
        <input name="email" type="email" />
        <input name="name" type="text" />
        <script>
          document.body.addEventListener("input", (e) => {
            console.log("type:", e.type, "value:", e.target.value);
          });
          document.body.addEventListener("change", (e) => {
            console.log("type:", e.type, "value:", e.target.value);
          });
        </script>
      </body>
    </html>