The setup in question can be tested and altered here: http://jsfiddle.net/5hAQ8/9/
I have a small form (basically just an input field with a clear-button). The JavaScript is trivial and just illustrates the problem. Basically it's three listeners on input (keyup), button (click/tap) and form (submit). The HTML is very simple:
<form>
<input>
<button>X</button>
</form>
The X is intended to clear the field, but that's not the point. When someone presses enter, even while the input is in focus, the button will get triggered. You may test this yourself in the linked jsfiddle above.
Once you press enter inside the form, you will see three alerts: one for the input, one for the button, one for the form. I can't understand why the button and the form would be involved at all?
My understanding of DOM events would have been a keyboard-event originating from the input, bubbling up to document, but I took every measure to cancel that event. So my question is threefold:
<button>
at all?keyup
?preventDefault
s / stopPropagation
s kick in.This answer goes back to details in the comments of the question. Thanks to Pointy for many of the details.
why does the event get to button and why click/tap
The default form submit (as defined in html5 spec). Apparently this is triggering click (which i wasn't expecting).
why doesn't the preventDefault kicks in
Implicit submission of the form is triggered before keyup. This answers why preventDefault has no chance. It appears not to be standardized, but every browser i tested did this.
Possible solutions
I think i'll go with keydown
or keypress
for keyCode==13, and keyup for the rest. Seems the least hackish solution to me. (suggested by ninty9notout, Thanks!)
This answers the three-part question pretty well. Thank you everybody who contributed.