When button is clicked, click events bubble up to form and execute the proper callbacks. However, after the button is deleted, formSubmitCallback
isn’t triggered which theoretically should be, due to the submit event. I can’t find exactly why this happens. Is the submit event called somehow after the DOM is updated? I’m not looking for a solution to this, but rather an explanation for the behavior.
HTML:
<form onsubmit="formSubmitCallback()" onclick="formClickCallback()">
<div onclick="divCallback()">
<button id="button" onclick="buttonCallback()">
click me
</button>
</div>
</form>
JS:
function buttonCallback() {
console.log("button")
document.getElementById("button").remove()
}
function divCallback() {
console.log("div")
}
function formClickCallback() {
console.log("form click")
}
function formSubmitCallback() {
console.log("form submit")
}
Result:
"button"
"div"
"form click"
2
Answers
I think you need to do
instead of
so that the form knows that the button is supposed to submit the it.
A quick google reveals that: "a div usually needs at least a non-breaking space ( ) in order to have a width".
So I guess because your div doesn’t have that, it takes up 0 pixels, thus can’t be clicked on the screen
If you just add any text in the div, then the second and third callbacks will fire again: