If you want to enhance the functionality of jQuery's fn
Object by incorporating a function that manages triggering callback functions based on key presses and Regex matching, there is a solution.
A while back, I created a similar response. Initially, it only supported regex matching for individual keys, but after some adjustments, it now accommodates multiple key combinations.
$.fn.selectedKey = (function () {
var keys = "";
var last = "";
var key = "";
return function (cb, data) {
def.call(data, {
ctrlKey: 2,
altKey: 2,
invert: 0,
filter: /.*/,
preventDefault: false
});
function validate(e) {
var exp = new RegExp(e.data.filter.replace(/\\\\(\d)/g, String.fromCharCode("$1")));
var c = !!(e.data.ctrlKey ^ e.ctrlKey ^ 1 > 0);
var a = !!(e.data.altKey ^ e.altKey ^ 1 > 0);
return (exp.test(keys) && (c && a));
}
function def(obj) {
for (var prop in obj) {
this[prop] = this[prop] || obj[prop];
}
}
this.keypress(data, function (e) {
key = e.char = String.fromCharCode(e.keyCode || e.which);
keys += (!!~keys.indexOf(key)) ? "" : key;
key = key["to" + (e.shiftKey ? "Upper" : "Lower") + "Case"]();
keys = keys["to" + (e.shiftKey ? "Upper" : "Lower") + "Case"]();
if (e.data.preventDefault) e.preventDefault();
if ((validate(e) != e.data.invert) && keys != last) {
cb(e);
last = keys;
}
});
if (!this.data("keyupBound")) {
this.keyup(data, function (e) {
key = e.char = String.fromCharCode(e.keyCode || e.which);
var t = keys.toLowerCase().split("");
t.splice(t.indexOf(e.char), 1);
keys = t.join("");
last = keys;
});
this.data("keyupBound", true);
}
};
})();
$("body").selectedKey(function (e) {
console.log("All lowercase letters, numbers, and 'A': " + e.char);
}, {
filter: "^[a-z]|[0-9]|A$",
ctrlKey: 2,
altKey: 2
});
$("body").selectedKey(function (e) {
console.log("KeyCode 2 " + e.char); // Ctrl + b
}, {
filter: "\\2",
ctrlKey: 1,
altKey: 2
});
You can also apply filter:/.{4,5}/
to trigger actions when any 4 to 5 keys are pressed simultaneously
For instance, the following code triggers when A + S + D are pressed together:
$("body").selectedKey(function (e) {
console.log("ASD has been pressed");
}, {
filter: "^ASD$",
ctrlKey: 2,
altKey: 2
});
Check out a functioning demo on JSBin
Edit Note: Resolved continuous triggering issue when holding keys if validation was true
Edit2: Corrected the usage of the last
variable