Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle ctrl+arrow in Javascript?

I've noticed an problem when trying to catch keyboard shortcut: CTRL + an arrow.

I've handled keydown event. Now when I hold CTRL key then keydown event is fired once. If I hold an arrow (so that now I'm holding CTRL + an arrow) it doesn't fire another event. Is it forbidden from any reason? I guess I've already encountered this problem in Opera a few years ago and there was an option for it in browser.

My results:

  • holding CTRL, press an arrow -- fires event for CTRL and doesn't fire an event for an arrow

  • press CTRL + an arrow at once -- fires one event but only with keycode of CTRL.

  • holding CTRL, press a letter (eg. S) -- works as expected

  • press CTRL + letter (eg. S) -- works as expected

(Results are identical in Chrome and Firefox. Is the behaviour described above a standard?)

I'm using:

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

The question is: what might be the problem?

like image 986
Martin Vseticka Avatar asked Apr 22 '10 18:04

Martin Vseticka


1 Answers

You should check if the event.ctrlKey flag is true, something 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;
      //...
    }
  }
};

Check an example here.

like image 186
Christian C. Salvadó Avatar answered Sep 25 '22 15:09

Christian C. Salvadó