I'm trying to make a script to detect if a certain key is being pressed, but the only reasonable thing I could think of was this.
onkeydown('F12'){
myFunction()
}
How would I do this? Thanks!
I'm trying to make a script to detect if a certain key is being pressed, but the only reasonable thing I could think of was this.
onkeydown('F12'){
myFunction()
}
How would I do this? Thanks!
Add an event listener for the "keydown" (or "keyup") action. To get the specific key that was pressed use "event.key".
document.addEventListener("keydown", function(e){
var key = e.key
})
using keyCode you can get the specific key. This example works if you press enter keyword (code 13). Check this out: https://keycode.info/
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
console.log('Hello world');
}
});
You should listen for the keydown
event and check its e.key
property:
const KEY_HANDLERS = {
F1: () => console.log('You pressed F1.'),
ArrowUp: () => console.log('You pressed ↑.'),
KeyA: () => console.log('You pressed A.'),
};
document.addEventListener('keydown', (e) => {
e.preventDefault();
const handler = KEY_HANDLERS[e.code];
if (handler) {
handler();
return;
}
console.log('Pressed a key without a handler.')
});
If you need to check KeyboardEvent's properties values such as e.key
, e.code
, e.which
or e.keyCode
, you can use https://keyjs.dev:
Disclaimer: I'm the author.
Maybe this is what you are looking for:
var inputForm = document.getElementById("taskInput");
inputForm.addEventListener('keydown', function(event) {
console.log("You are pressing this key :", String.fromCharCode(event.keyCode));
});
<input type="text" id="taskInput"/>