The browser does not process keystrokes in a textbox (<input type="text">
) until after all JS event handlers are finished.
In my app, though, I have a textbox nested inside an outer widget. The outer widget is not aware of the textbox’s existence, but I want to block it from processing keystrokes if the textbox is able to handle the same keystrokes. So I want to do something like this:
function onInputKeyDown(e) {
const textbox = e.target as HTMLInputElement;
const selStart = textbox.selectionStart, selEnd = textbox.selectionEnd;
const content = textbox.textContent;
e.invokeDefault() // doesn't exist
if (selStart !== textbox.selectionStart || selEnd !== textbox.selectionEnd
|| content !== textbox.textContent)
e.stopPropagation();
}
I tried simulating “invokeDefault” with e.preventDefault(); e.target.dispatchEvent(new KeyboardEvent('keydown', e))
but it turns out that dispatchEvent
doesn’t cause default behavior, it just calls event handlers (the current event handler is re-entered) so the text field doesn’t change. Is there another way?