Detecting The Shift/Ctrl/Alt Keys

Description

This page demonstrates a technique for detecting the shift, ctrl and alt keys. It is quite simple, for example:

  • 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.

Demo

Shift/ctrl/alt key events are logged here, as well as when they modify the Enter key. Opera does not allow detection of the alt key and I think that's probably a good idea. IE handles ctrl+key differently than Opera or Mozilla, and this effect may be different depending on the OS (not sure).


Implementation

Here's the Javascript for this page.

<script type='text/javascript' src='../x_core.js'></script>
<script type='text/javascript' src='../x_event.js'></script>
<script type='text/javascript'>

var shiftMode = false; // if true the shift key is down
var ctrlMode = false; // if true the ctrl key is down
var altMode = false; // if true the alt key is down 

window.onload = function()
{
  log();
  xAddEventListener(document, 'keydown', docOnKeydown, false);
  xAddEventListener(document, 'keyup', docOnKeyup, false);
  xAddEventListener(document, 'keypress', docOnKeypress, false);
}

function docOnKeydown(ev)
{
  var e = new xEvent(ev);
  switch (e.keyCode) {
    case 16:
      shiftMode = true;
      log('shift down');
      break;
    case 17:
      ctrlMode = true;
      log('ctrl down');
      break;
    case 18:
      altMode = true; // not supported by Opera and I agree
      log('alt down');
      break;
  }
}

function docOnKeyup(ev)
{
  var e = new xEvent(ev);
  switch (e.keyCode) {
    case 16:
      shiftMode = false;
      log('shift up');
      break;
    case 17:
      ctrlMode = false;
      log('ctrl up');
      break;
    case 18:
      altMode = false; // not supported by Opera and I agree
      log('alt up');
      break;
  }
}

function docOnKeypress(ev)
{
  var e = new xEvent(ev);
  if (e.keyCode == 13) {
    if (shiftMode) log('shift+enter');
    if (ctrlMode) log('ctrl+enter');
    if (altMode) log('alt+enter');
  }
}

function log(s)
{
  var ta = xGetElementById('log');
  if (s) ta.value += s + '\n';
  else ta.value = '';
}
</script>

Related Demos