5

I have an event listener in Javascript, I can tell whether a key event is Ctrl (e.keyCode == 17), but how can I know this Ctrl comes from the right one or left one?

Tom
  • 43,583
  • 4
  • 41
  • 61
Thomson
  • 20,586
  • 28
  • 90
  • 134

6 Answers6

6

Just a quick note: I wouldn't base an architecture / design on the availability of the right control key - many laptop keyboards may not have two control keys.

3

I don't think the keyCode is different.

You can use e.ctrlKey for a better way to determine if the control key was pressed.

It seems Flash can not tell which one is pressed either (either that or coded incorrectly).

alex
  • 479,566
  • 201
  • 878
  • 984
  • They are abstracted. E.g. I can choose a ton of different options for each of them in my Ubuntu Keyboard settings. – Ivo Wetzel Jan 04 '11 at 05:34
  • You can definitely write software that differentiates between the two on a low level, so no, it can't be abstracted on the hardware level. It's probably abstracted on the OS level, though. – Sasha Chedygov Jan 04 '11 at 08:26
  • MSIE can differentiate the left and right Ctrl key, see my answer on that point. – Julien Kronegg Feb 07 '13 at 15:41
1

MSIE provides a ctrlLeftproperty on most events. The property values are:

  • true if the left key was pressed during the event
  • false if the left key was not pressed.

You can combine event.ctrlKey and event.ctrlLeft to determine if the right Ctrl key was pressed:

if (event.ctrlKey) {
    if (event.ctrlLeft) {
        // left Ctrl key pressed
    } else {
        // right Ctrl key pressed
    }
} else {
    // no Ctrl key pressed
}

Note that the ctrlLeftproperty in a keyup is undefined because the Ctrl key is not pressed anymore.

Tested under MSIE7 and MSIE9. Does not work under Firefox.

See http://help.dottoro.com/ljqlvhuf.php for details.

Julien Kronegg
  • 4,968
  • 1
  • 47
  • 60
1

If you traced it you will find the same key is used for both (17) .. I think it is not possible to differentiate

Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
1

I don't know if it was available when this was asked, but you can distinguish left- from right-ctrl, as well as alt and shift. You can now use the KeyboardEvent.DOM_KEY_LOCATION_* properties to make this distinction.

See Can javascript tell the difference between left and right shift key?

Be aware though, I discovered that Chrome appears to have a defect in its implementation. See How can I distinguish left- and right- shift, ctrl, and alt keys onkeyup in Chrome with Javascript

Community
  • 1
  • 1
Jim Noble
  • 492
  • 6
  • 12
1

There is event.location property for left ctrl key it will be 1 for right one 2, you can check browser support on canIuse

if (e.which == 17) {
   if (event.location == 1) {
      // left ctrl key
   } else if (event.location == 2) {
      // right ctrl key
   }
}
jcubic
  • 61,973
  • 54
  • 229
  • 402