Is is possible to press two keys with an onclick function?
I am hoping to press 'shift' & '=' at the same time with a button.
I found this code on this post: How to fire keyboard events in Javascript using onClick?
let elem = document.querySelector("input");
elem.addEventListener("keypress", (e) => {
if(e.key === "d"){
keyDPressed();
}
});
elem.addEventListener("click", (e) => {
let eve = new KeyboardEvent('keypress',{ key : "d"})
e.target.dispatchEvent(eve);
});
function keyDPressed(e) { //function that gets called when key D is pressed
console.log("d was pressed");
}
<input value="Click here" type="button">
CodePudding user response:
Yes, by add shiftKey: true
to the KeyboardEvent
constructor options.
let elem = document.querySelector("input");
elem.addEventListener("keypress", (e) => {
if (e.key === '=' && e.shiftKey) {
keyEqualPressed(e)
}
});
elem.addEventListener("click", (e) => {
let eve = new KeyboardEvent('keypress',{ key : "=", shiftKey: true, })
e.target.dispatchEvent(eve);
});
function keyEqualPressed(e) { //function that gets called when key = && shift are pressed
console.log("Key equal and shift pressed");
}
<input value="Click here" type="button">
CodePudding user response:
You would set shiftKey or one of the other modifier keys
let elem = document.querySelector("input");
elem.addEventListener("keypress", (e) => {
if (e.key === "d") {
keyDPressed(e);
}
});
elem.addEventListener("click", (e) => {
elem.dispatchEvent(new KeyboardEvent("keypress", {
key: "d",
altKey: false,
shiftKey: true,
ctrlKey: false,
metaKey: false,
}));
});
function keyDPressed(e) { //function that gets called when key D is pressed
console.log("d was pressed", e.shiftKey);
}
<input value="Click here" type="button">