Sayan
Sayan

Reputation: 23

How to create shortcut key for calling an event in jquery?

How to create shortcut key for calling an event in jQuery (Like if I press Alt + A then call a button click function. But not if Alt + V + A).

Upvotes: 2

Views: 151

Answers (1)

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

I don't know if this is the best solution, but maybe helps:

Warning: this is not battle tested solution

var pressedKeys = [];

document.addEventListener('keydown', function(e) {  
    if(e.altKey){
        var idx = pressedKeys.indexOf(e.which);
        if(idx < 0) pressedKeys.push(e.which);
    }
});

document.addEventListener('keyup', function(e) {
    // 65 means A
    if (e.altKey && e.which == 65){
        if(pressedKeys.length === 2)
            console.log("Alt + A shortcut combination was pressed");  
    }

    var idx = pressedKeys.indexOf(e.which);
    if(idx > -1) pressedKeys.splice(idx, 1);
});

You can see above code in action, here on codepen

Upvotes: 1

Related Questions