Photo of Declan Kelly

Declan Kelly

Full-Stack Web Developer

Detecting Left/Right Shift Key Press in JavaScript

1 min read · tagged javascript, programming

Currently I am working on a project for fixing a touch typing habit I have. I type by pressing the shift key always using my left little finger, rather than the proper way of using the shift key in the opposite hand to the one typing the character (e.g. the left shift key should be used when typing ‘I’, and the right shift key when typing ‘X’ on a QWERTY keyboard). It is possible to detect which shift key is being pressed using the following JavaScript code below:

  if (event.which == 16) {
    if (event.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT){
      alert("Left shift key!");
    } else if (event.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT){
      alert("Right shift key!");

event.location and KeyboardEvent are part of the [UI Events (formerly DOM Level 3 Events) specification]( "W3C - UI Events (formerly DOM Level 3 Events)"). The code is supported in Chrome, Firefox (15+) and IE (9+), but is not supported in many versions of Safari, Opera and mobile browsers.