3

I am looking for a general solution to detect braces: { or }. I have an azety keyboard and I need to use the ALT GR stroke to type them, they are respectively located on the 4 and + keys.

As it is not the same on qwerty keyboard, and probably other dispositions, I can not know if these characters are being typed just with the information given by the event returned by the keyup listener, I just know that the 4 has been pressed (Chrome does not event let me know that the alt gr is pushed).

Yet, if I use the keypress event, I get the correct code. But keyup is preferable for me.

var element = document.getElementById('textbox');

element.onkeyup = function(evt){    
    console.log("keyup");    
    console.log(evt.which);
};


element.onkeypress = function(evt){    
    console.log("keypress");    
    console.log(evt.which);
  
};
<textarea id="textbox"></textarea>

with that code, I get this output when I type a {:

keypress
123 // { key code
keyup
52 // 4 key code
keyup
225 //alt gr key code

So, is there a solution, independant to the keyboard disposition to detect braces?

Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52
  • 2
    Actually not possible using keydown/up, until all browsers support [`key` property](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). On my keyboard I need to press AltGr + 7 and AltGr + 0 to get curly braces, you can guess that they have different keycodes than your keyboard. AltGr is actually the same as Ctrl + Alt, afaik they can be detected in Chrome too. – Teemu Aug 11 '15 at 21:33
  • _keyup_ and _keydown_ give you the physical locations of keys, _keypress_ gives you the printable characters. – Paul S. Aug 11 '15 at 21:50

1 Answers1

2

AltGr is the same as Ctrl-Alt you could ask for the modifiers while checking.

You must know that the same keyboard could change de configuration of the position of each, keys. I'm have a Spanish/English windows configuration and I change the layout several times in the same day (that changes the position of { and }).

You must use keypress

Emilio Platzer
  • 2,327
  • 21
  • 29
  • It is only the same on Windows: https://en.wikipedia.org/wiki/AltGr_key#Control_.2B_Alt_as_a_substitute. I agree with you, I can not have reliable solution without using keypress – Gaël Barbin Aug 12 '15 at 07:10