Skip to content Skip to sidebar Skip to footer

How To Do Something If The User Presses Two Keys In Javascript

So I wrote this script so that you can have keyboard shortcuts on your website, and I was wondering how to do multiple keys (ie instead of doing just the 'left arrow' key, it would

Solution 1:

The event object provided in jQuery tells you if the ctrl key is being pressed.

$(document).on("keydown", function (event) {
    if (event.ctrlKey && event.which === arrow.left) {
        console.log("You pressed left, and control.");
    }
});

Demo: http://jsfiddle.net/zcMXR/

Solution 2:

jQuery already does that. Along with tracking which key was pressed, you can also get information on whether the key was pressed in combination with alt, ctrl or shift with the properties shown below:

$(document).keydown(function(e) {
      console.log('key code is: ' + e.which + ' ' + (e.ctrlKey ? 'Ctrl' : '') + ' ' +
            (e.shiftKey ? 'Shift' : '') + ' ' + (e.altKey ? 'Alt' : ''));
});

So, to check if the key combo is Ctrl + Up, your condition is going to look like:

if( e.which == 38 && e.ctrlKey ){
    console.log('You pressed Ctrl+Up');
    ...
}

Post a Comment for "How To Do Something If The User Presses Two Keys In Javascript"