Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect keyboard modifier (Ctrl or Shift) through JavaScript

Tags:

javascript

I have a function which detect max length. but the problem is that when the max length reached Ctrl+A combination does't work. How can I detect Ctrl+A combination through javascript.

This is my maxlength code.

if (event.keyCode==8 || event.keyCode==9 || event.keyCode==37 || event.keyCode==39 ){
        return true;
} else {            
        if((t.length)>=50) {    
            return false;
        }   
}
like image 832
coder Avatar asked Nov 24 '12 08:11

coder


People also ask

How do you detect if a key is being pressed in JavaScript?

Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

Is Ctrl a modifier key?

Examples of modifier keysOn an IBM compatible computer, modifier keys include Alt, Ctrl, Shift, and the Windows key. On the Apple Macintosh computer, the Control, Option, Command, and Shift keys are modifier keys. Additionally, most laptop and some desktop keyboards contain an Fn modifier key.

Which key is modifier key on keyboard?

On a Windows keyboard, the modifier keys are Shift, Alt, Control, and the Windows key. On a Mac keyboard, the modifier keys are Shift, Control, Option, and Command (often called the Apple key).


2 Answers

Check event.ctrlKey:

function keyHandler(event) {
    event = event || window.event;
    if(event.keyCode==65 && event.ctrlKey) {
        // ctrl+a was typed.
    }
}
like image 109
gilly3 Avatar answered Nov 09 '22 11:11

gilly3


key codes:

shift   16
ctrl    17
alt     18

your jQuery:

$(document).keydown(function (e) {
    if (e.keyCode == 18) {
        alert("ALT was pressed");
    }
});

JavaScript Madness: Keyboard Events

like image 33
DolDurma Avatar answered Nov 09 '22 13:11

DolDurma