Event.key undefined in mobile browsers for keyboard activation, keystrokes and keystrokes

The following code should simply suppress any key press and instead press the key down. This works great on desktop, however event.key

there is undefined on mobile (safari and chrome) .

<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 available, but casting them to a string will give me unwanted results on different keyboard layouts and languages, especially with special characters.

Is there anyway to get the key value directly?

Here's a sample code: https://codepen.io/anon/pen/pryYyQ

+3


source to share


1 answer


The only workaround is to get the key code and pass it to a 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;
})

      

+2


source







All Articles