jcubic
jcubic

Reputation: 66560

CTRL key check for right ALT in javascript

I have simple code like this:

var input = document.getElementsByTagName('input')[0];
var pre = document.getElementsByTagName('pre')[0];
var ctrl = false;
input.addEventListener('keydown', function(e) {
  if (e.which == 17) {
    ctrl = true;
  }
  pre.innerHTML += 'keydown: ' + JSON.stringify({
    location: e.location,
    ctrlKey: ctrl,
    altKey: e.altKey,
    which: e.which
  }) + '\n';
});
input.addEventListener('keyup', function(e) {
  if (e.which == 17) {
    ctrl = false;
  }
  pre.innerHTML += 'keyup: ' + JSON.stringify({
    location: e.location,
    ctrlKey: ctrl,
    altKey: e.altKey,
    which: e.which
  }) + '\n';
});
<input>
<pre>
</pre>

And in google chrome the same as in Firefox and IE10 when you press right alt the e.ctrlKey is set to true, I've try to fix it by adding global variable ctrl and set it to true on keydown and set to false on keyup but that didn't fix it because when you press right alt keydown for CTRL is fired and the same for keyup.

It this a bug or is it in a spec somewhere?

Is there a way to know if left alt was pressed without Ctrl key?

Upvotes: 0

Views: 618

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Right Alt, typically Alt Gr, is indeed equivalent to Ctrl+Alt. I don't know why, but it is.

So it's normal to get both Ctrl Key and Alt Key from it.

Upvotes: 1

Related Questions