Search code examples
javascriptjqueryeventskeyboardmultilingual

Detect entered character with JavaScript


I'd like to start an action (enabling autocomplete) when user types '@'. I have jQuery available.

Usually on a QWERTY keyboard, it is like this:

$('textarea').live('keydown', function(e) {
  if (e.which === 50) {
    console.log('@ has been entered.');
  }
});

However it does not work correctly on an AZERTY keyboard. The keyCode = 50 corresponds to the é~/2 key. To type '@' in AZERTY keyboard, it is AltGr + à@/0 key.

Edit: Autocomplete starts when @ is entered, and only after that. Example, when someone enters "Hello @" then it starts, however when he types "Hello @nothing else" the complete won't do anything. Example: http://mrkipling.github.com/jQuery-at-username/ (it works only on QWERTY keyboard).


Solution

  • Use keypress instead of keydown. While keydown relates to every press of a key, keypress relates to the translated characters, so for example a can be different to a while the shift key is pressed, composed characters work, dead-keys work, and other differences in keyboard mappings are handled.