'How to emulate ESC keypress on a webpage by javascript?
How to emulate ESC keypress on a webpage by javascript?
Thanks a lot for the help!
Solution 1:[1]
As there is no answer to the question, here is a possible solution from here.
function invokeEscKey() {
var ev = document.createEvent('KeyboardEvent');
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 27, 0);
document.body.dispatchEvent(ev);
}
Solution 2:[2]
Simulate Esc key using Javascript (Tested in Firefox and Chromium):
window.dispatchEvent(
new KeyboardEvent("keydown", {
altKey: false,
code: "Escape",
ctrlKey: false,
isComposing: false,
key: "Escape",
location: 0,
metaKey: false,
repeat: false,
shiftKey: false,
which: 27,
charCode: 0,
keyCode: 27,
})
);
To find correct values of any key:
- paste below to dev tools:
document.addEventListener(
"keydown",
(e)=>{console.log(e)}
);
Press the desired key.
copy values from logs.
ref: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
Solution 3:[3]
You mean something like this
$(document).delegate('input','keypress', function(e){
code = e.keyCode ? e.keyCode : e.which;
if(code=== 27){
alert('esc pressed');
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CennoxX |
| Solution 2 | GorvGoyl |
| Solution 3 | Om3ga |
