How to handle Ctrl + arrow in Javascript?

I noticed a problem when trying to catch a key combination: CTRL+ arrow.

I handled the keydown event. Now, when I hold the key CTRL, the keydown event is fired once. If I hold the arrow (so now I hold the CTRL+ arrow), it does not fire another event. Is this prohibited for any reason? Probably, I already encountered this problem in Opera several years ago, and there was an option in the browser.

My results:

  • CTRL, press the arrow - raises the event CTRLand does not fire the event for the arrow

  • press CTRL+ arrow simultaneously - one event is triggered, but only with a key code CTRL.

  • CTRL, press a letter (for example S) - works as expected

  • press CTRL+ letter (for example S) - works as expected

(The results are identical in Chrome and Firefox. Is the behavior described above standard?)

I use:

  • function OnKeyDown(e) { }
  • e.ctrlKey, e.which event properties

The question is, what could be the problem?

+5
source share
1 answer

You should check if the flag is really event.ctrlKeysomething like this:

document.getElementById('element').onkeydown = function (e) { 
  e = e || window.event;
  var keyCode = e.keyCode || e.which,
      arrow = {left: 37, up: 38, right: 39, down: 40 };

  if (e.ctrlKey) {
    switch (keyCode) {
      case arrow.left:
      //... handle Ctrl-LeftArrow
      break;
      //...
    }
  }
};

See an example here .

+10
source

All Articles