I have the following html snippet:-
<fieldset id="container">
<legend>Event Delegation Test</legend>
<button type="button" id="btn_select" name="select button">Select</button>
<input type="text" name="first" autofocus/>
<input type="text" name="second"/>
<input type="text" name="third"/>
<input type="text" name="fourth"/>
<input type="text" name="fifth"/>
<select name="Names">
<option>Tom</option>
<option>Dick</option>
<option>Harry</option>
</select>
</fieldset>
I have set event delegation on the fieldset (id="container") and added the change event thus:
document.getElementById("container").addEventListener("change", e => {
let el = e.target,
name = el.name,
value = el.value;
console.log("CHANGE element: %s has value %s", name, value);});
I have found that using the following code...
select.value = "Harry";
select.dispatchEvent(new Event("change"));
...isn't detected by the delegate handler.
BUT this does work...
select.value = "Harry";
let ce = new CustomEvent("change", {
bubbles: true,
cancelable: false
});
select.dispatchEvent(ce);
WHY?
I have been unable to find any information as to this particular use case peculiarity Any enlightenment would be greatly appreciated.
You have to explicitly specify that the event propagates:
new Event("change", {"bubbles": true});
The default value for the event propagation (propertie bubbles
) is false. That is why your delegate handler is not receiving the change
event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With