Search code examples
javascriptfirefoxkeypress

How to make FF insert character into input that was added and focused by onkeypress handler?


I have a page with onkeypress handler which inserts input element and sets focus on it.

The idea is that when user starts typing, the input shows up and the text is entered into this new input.

This works fine on Chrome 67 and IE 11, but on FF (52.9.0) the first character typed (the one which triggered creation of the input) is not entered into the input.

I think the other browsers' behavior is correct, because according to w3c example onkeypress event occurs before "Any default actions related to this key, such as inserting a character in to the DOM", so when the default action is performed the new input should already have focus. However this is not working that way in FF.

I've reduced the issue to this test case:

<html>
<head>
   <script>
       var input = null;
       function cancelEdit() {
           document.body.removeChild(input);
           input = null;
       }
       function handleKeyPress(e) {
           if (input === null) {
               input = document.createElement("input");
               input.addEventListener("blur", cancelEdit);
               document.body.appendChild(input);
               input.focus();
           }
       }
    </script> 
</head>
<body onkeypress="handleKeyPress(event)">
    Press a key to start editing
</body>

This is also available as jsfiddle

Now the question is: how to make it behave in FF the same way as in the other browsers?

My browser versions: Chrome 67, IE 11, FF 52.9.0. All on Windows 7.


Solution

  • While I can't test on IE11 right now. You could try changing onkeypress to onkeydown

    Tested it on Chrome latest and Firefox 61 (before the change the issue was replicated)