xxxxxxxxxx
let pressedKeys = [];
document.addEventListener("keydown", handleKeydown);
document.addEventListener("keyup", handleKeyup);
function handleKeydown(e) {
// check if the key already exists in the array
if (!pressedKeys.includes(e.key)) {
// add the key to the array once it's pressed
pressedKeys.push(e.key);
// if you want the code to execute only once if the
// user holds the key down, put all the code inside this
// if block, otherwise put it outside
if (
pressedKeys.includes("Control") &&
pressedKeys.includes("c") &&
pressedKeys.length == 2
) {
e.preventDefault();
console.log("Control + c");
return;
}
if (
pressedKeys.includes("Control") &&
pressedKeys.includes("a") &&
pressedKeys.includes("b") &&
pressedKeys.length == 3
) {
console.log("Control + a + b");
return;
}
}
}
function handleKeyup(e) {
// remove the key from the array once it's released
const index = pressedKeys.indexOf(e.key);
pressedKeys.splice(index, 1);
}
xxxxxxxxxx
//youtube-video :
// https://www.youtube.com/watch?v=O5fUMaIvhMg&ab_channel=YesMYdev
// javascript key combination, for this example 'ctrl + z'
//checker
let combination = false;
document.addEventListener('keydown', function(e){
if( e.key == "Control" && !combination ){
combination = true;
//you have 500ms second to execute the combination,
//otherwise you will have to press "ctrl (control)" again
const timeExe = setTimeout(() => {
combination = false;
}, 500);
}
if((e.key == ("z" || "Z")) && combination ){
combination = false;
console.log("the combination worked successfully");
}
})