Search code examples
javascriptwebkeyboardweb-audio-apiqwerty

Is it possible to get a keypressed position instead of its keyCode or char?


I'm building a musical piano in javascript that allows people to play using their computer keyboards. I've mapped the notes of a piano to a QWERTY keyboard layout. However, if someone has a different keyboard layout, for example AZERTY the order of the notes is wrong.

Is it possible to get the keypressed position rather than the keycode? I'm not interested in the value of the key, just it's position on the keyboard.

If this is possible the piano would work globally and I wouldn't have to create separate key maps for all different language types.


Solution

  • In the future use KeyboardEvent.code

    A KeyboardEvent property representing the physical key that was pressed, ignoring the keyboard layout and ignoring whether any modifier keys were active.

    https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

    Currently only available in Firefox and Chrome Canary.