jQuery Capture Multiple Key Press Combinations

By Sam Deering

You may have read a previous post on how to capture a single key press using jQuery. In this example you can capture multiple key presses in combinations.

The array (arrShortCut) defines the following:

  1. a name (for reference only)
  2. a keypad code
  3. a function to execute in the variable iShortCutControlKey

if the control key activates the state” to keyup if the control key “off state”, if verified a key keydown a “no control” to “active status” look in the array if there is a preset for that key, if the function call “execShortCut” that … executes the function;

//to test use CTRL + Z = alert (2)

var arrShortCut = [{ name: 'test1', key: 15, fx: 'alert(1);' }, { name: 'test2', key: 90, fx: 'alert(2);'}];

var iShortCutControlKey = 17; // CTRL;
var bIsControlKeyActived = false;

$(document).keyup(function(e) {
    if (e.which == iShortCutControlKey) bIsControlKeyActived = false;
}).keydown(function(e) {
    if (e.which == iShortCutControlKey) bIsControlKeyActived = true;
    if (bIsControlKeyActived == true) {
        jQuery.each(arrShortCut, function(i) {
            if (arrShortCut[i].key == e.which) {

function execShortCut(fx) {
  • Kenneth R Wilson Jr.

    Great snippet here, is it possible to capture 2 consecutive key press such as the space key and then the @ symbol to trigger an event?



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.