Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect shift + key down in javascript? [duplicate]

Tags:

javascript

Possible Duplicate:
How to catch enter keypress on textarea but not shift+enter?

How can I detect shift + key down in JavaScript?

like image 273
Bart Avatar asked Sep 20 '11 02:09

Bart


People also ask

How to detect shift in JavaScript?

The mouseEvent shiftKey property is used to define whether the shift key is pressed or not. It is a boolean value. When the shift key is pressed then on click of the mouse left button, it returns true and if the shift key is not pressed then it returns false.

How do you know if shiftKey is pressed?

The shiftKey property returns a Boolean value that indicates whether or not the "SHIFT" key was pressed when a key event was triggered.

What does keydown do in JavaScript?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What is keydown function?

The keydown event occurs when a keyboard key is pressed down. The keydown() method triggers the keydown event, or attaches a function to run when a keydown event occurs. Tip: Use the event. which property to return which keyboard key was pressed.


2 Answers

event.shiftKey is a boolean. true if the Shift key is being pressed, false if not. altKey and ctrlKey work the same way.

So basically you just need to detect the keydown as normal with onkeydown, and check those properties as needed.

like image 199
Niet the Dark Absol Avatar answered Oct 21 '22 21:10

Niet the Dark Absol


var onkeydown = (function (ev) {
  var key;
  var isShift;
  if (window.event) {
    key = window.event.keyCode;
    isShift = !!window.event.shiftKey; // typecast to boolean
  } else {
    key = ev.which;
    isShift = !!ev.shiftKey;
  }
  if ( isShift ) {
    switch (key) {
      case 16: // ignore shift key
        break;
      default:
        alert(key);
        // do stuff here?
        break;
    }
  }
});
like image 21
Adam Eberlin Avatar answered Oct 21 '22 20:10

Adam Eberlin