Keycode detection on AZERTY vs. QWERTY

2.4k Views Asked by At

How can I in JavaScript detect the typing of a question mark on AZERTY keyboard ? On QWERTY keyboard a question mark produces the code 191, but on AZERTY it seems to produce code 188 (comma on QWERTY). Or should I distinguish between both keyboards in JavaScript, but how ?

2

There are 2 best solutions below

0
On

The fastest solution I can think of is to compare the key with the actual question mark, so something like this would be a good solution.

document.addEventListener('keydown', function(event) {
    if (event.key && event.key === '?') {
        // your code goes here
    }
}, true);
0
On

If you want to detect the character being typed, use KeyboardEvent.key, not KeyboardEvent.code -- the key property will contain either the character that was typed (like "?"), or a string like "Shift" or "ArrowUp" for special keys. The location of the key on the keyboard won't affect the result.

$("#f").on("keydown", function(ev) {
  $(this).val(ev.key);
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="f" autocomplete="off">