Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Alt Gr (Alt Graph) modifier on key press

In the javascript Event object, there are some boolean values to check if modifier keys are pressed:

  • ctrlKey: CTRL key.
  • altKey: ALT key.
  • altLeft: ALT left key. Only for IE.
  • altGraphKey: ALTGR key. Only for Chrome/Safari.

However, there are some issues:

  • IE and Chrome set ctrlKey to true and altKey to true when you press the ALTGR modifier.
  • Firefox sets ctrlKey to false and altKey to true when you press the ALTGR modifier, as only ALT has been pressed.
  • Chrome has the altGraphKey property, but it is always undefined.

Question: how can I difference between an ALT+CTRL or an ALTGR key press? Specially in Chrome.

like image 613
Nitz Avatar asked May 18 '12 17:05

Nitz


People also ask

How do I enable Alt Gr on my keyboard?

Just like how you use the Control key for Ctrl + C, you can use ALT GR + key which also houses the special or the accented letter. Windows allows emulating Alt GR when you press Ctrl + Alt keys together.

What does Alt Gr F11 do?

Ctrl + Alt + F11 sort of puts the GUI to sleep, and puts you into a virtual terminal mode, something like the old fashion ttys. Once in this mode you can choose between 6 different tty input screens.


3 Answers

The altGraphKey in webkit browsers no longer appears to exist (as at September 2013) and the behaviour of Firefox has changed. Browser behaviours for the AltGr key currently appear to be:

  • Webkit (Chrome) - ctrlKey: true, altKey: true
  • IE 8 - ctrlKey: false, altKey: true
  • IE 10 - ctrlKey: true, altKey: true
  • Mozilla (Firefox) - ctrlKey: true, altKey: true

Which is to say, they are all currently consistent (apart from IE8, which remains consistently inconsistent).

The following snippet should catch Alt Gr - but not Alt or Ctrl - in modern browsers. You will need a special case for IE8 however:

if (event.ctrlKey && event.altKey) {
    // Appears to be Alt Gr
}
like image 71
Jason Avatar answered Sep 26 '22 19:09

Jason


Disclaimer: I don't have a keyboard that has this key, so I can't test myself, but the spec says that can use the key property. This may be a good solution if you only need to support browsers that implement it (at time of writing, only Safari doesn't). You can check if the value is "AltGraph".

window.onkeydown = function (e) {
  if (e.key === 'AltGraph') {
    console.log(e.key);
  }
};
like image 30
Frank Tan Avatar answered Sep 26 '22 19:09

Frank Tan


Worth mentioning is that it is possible to detect this in modern browser by checking the location of the alt key event.

See: Is there a way to detect which side the Alt key was pressed on (right or left)?

like image 40
Robin Andersson Avatar answered Sep 22 '22 19:09

Robin Andersson