Olof
Olof

Reputation: 544

Nested web components and event propagation

I have two web components. First is an input field. Second is a form with a button. My page simply put the input web component into the form web component.

The input web component manage the blur event to do some validation. This validation, in case of error, add some elements into the DOM. The form web component manage the click event on the button to do some actions.

If the focus is in the input and I click the button, the blur event is fired, but not the click event. If I remove the code who add some elements into the DOM (in the blur event), the two events are fired !

Here is a fiddle to demonstrate that : https://jsfiddle.net/2guc1rkj/

  1. Open the console
  2. Put the focus on the input and click the button -> the console display 'Blur'
  3. comment line 32 (parent.appendChild(content);), run Fiddle, put the focus on the input and click the button -> the console display 'Blur' and 'Click' !

The line to comment :

parent.appendChild(content);

Why my click event is not working when my blur event make some modification to the DOM ?

Upvotes: 0

Views: 832

Answers (1)

aug
aug

Reputation: 11714

The reason the click event doesn't trigger when you have the code for appending content is because appending the content moves the button. The events are triggered sequentially so it first triggers the blur, which then adds the content, shifts the button down, and then click does not happen on the button because the button is no longer there to receive the click.

When you comment the parent.appendChild, the button isn't shifting so it stays in place.

You can confirm this by simply moving the button above where it doesn't move around and isn't getting shifted by the elements you are appending.

https://jsfiddle.net/augburto/2guc1rkj/1/

Upvotes: 2

Related Questions