Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.key is undefined in mobile browsers for keyup, keydown and keypress

The following code is supposed to simply suppress any key press and add the pressed key to a div instead. This works fine on desktop, however on mobile (safari and chrome) event.key is undefined.

<html>
    <head></head>
    <body>
        <input />
        <div id="#test"></div>
        <script>
            var str = '';
            var el = document.getElementById('#test');
            document.addEventListener('keypress', function(event) {
                str += event.key;
                event.preventDefault();
                el.innerHTML = str;
            })
        </script>
    </body>
</html>

event.keyCode and event.keyIdentifier are both available but casting those to a string will give me unwanted results on different keyboard layouts and languages, especially with special characters.

Is there anyway to get the value of the key directly?

Here's a codepen example just in case: https://codepen.io/anon/pen/pryYyQ

like image 660
Philip Feldmann Avatar asked Aug 01 '17 09:08

Philip Feldmann


People also ask

Does Keydown work on mobile?

1 Answer. Show activity on this post. keydown should work, but you could use the input event which seems to have undesired effects on Android mobile...

Does Keyup work on mobile?

Found that keyup does not work on mobile phones.

What is Keyup Keydown and keypress?

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress . An uppercase "A" is reported as 65 by all events.

What is Keyup and Keydown in jQuery?

jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.


1 Answers

The only workaround is to get the keycode and cast it to String:

var str = '';
var el = document.getElementById('#test');
document.addEventListener('keypress', function(event) {
  const currentCode = event.which || event.code;
  let currentKey = event.key;
  if (!currentKey) {
    currentKey = String.fromCharCode(currentCode);
  }
  str += currentKey;
  event.preventDefault();
  el.innerHTML = str;
})
like image 112
Philip Feldmann Avatar answered Sep 19 '22 09:09

Philip Feldmann