Detecting The Shift/Ctrl/Alt Keys

Description

This page demonstrates two techniques for detecting the shift, ctrl and alt keys. The first technique is as follows.

  • The keydown listener sets shiftMode to true when event.keyCode == 16.
  • The keyup listener sets shiftMode to false when event.keyCode == 16.
  • The keypress listener now knows if the shift key is currently pressed.

The second technique simply reads the event properties shiftKey, ctrlKey and altKey.

Experiment with your own browsers because the results may be OS-dependent.

Demo

Shift/ctrl/alt key events are logged here.

Technique 1

Technique 2

Browser Tests

The following tests were made on Win2K.

Opera 7.51

Does not allow detection of the alt key.

Issues a keypress event between the keydown and keyup events when only the shift/ctrl/alt key is pressed - Moz and IE do not.

When a shift+key or ctrl+key is pressed, two keypress events occur between keydown and keyup.

Mozilla 1.7.2

Technique 1 can fail for the alt key when the menu is selected - because the keyup event is not seen.

IE 6.0

The keypress event doesn't fire at all when a ctrl+key combo is pressed. It does in Op and Moz.

Technique 1 can fail for the alt key when the menu is selected - because the keyup event is not seen.

Revision

24 March 05

Added the second technique and did more tests.

Related Demos

License

By your use of X and/or CBE and/or any Javascript from this site you consent to the GNU LGPL - please read it. If you have any questions about the license, read the FAQ and/or come to the forums.

Tech Support

Forum support is available at the X Library Support Forums.

Search

Cross-Browser.com

World Wide Web