1

I have a form that is dynamically added to the DOM and therefore I have to use event delegation.

I can not get this to fire and it looks to me like this event can only be attached to an input element

['change', 'blur'].forEach(event => {
  document.addEventListener(event, e => {
    if (e.target.closest('.dynamic-modal form input')) {
      const $input = e.target.closest('.dynamic-modal form input')
      console.log($input)
      // never logs on change and blur
    }

  })
})

How can I go about solving this?

dbzx10299
  • 722
  • 2
  • 14
  • 2
    The [`blur` event](https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event) does not bubble. For the [`change` event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) it should work. – Bergi Jun 24 '22 at 23:02
  • @Bergi In the capturing phase when the event reaches the target it is captured into the $input variable. Is it wrong that the blur and change events here are being attached to the document? – dbzx10299 Jun 24 '22 at 23:04
  • 1
    "*I have to use event delegation*" - no, you can also attach the event handlers dynamically when adding the form to the DOM. Can you show that code, please? – Bergi Jun 24 '22 at 23:04
  • Got it to work, thank you! I did not know that you could attach an event listener in this manner – dbzx10299 Jun 24 '22 at 23:08

0 Answers0