I am currently using this Javascript keypress code to fire events upon keypress:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
});
but what I am wondering is if I can instead of binding one key bind a combination of two keys. Could I possibly do something like:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39 && 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});
keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.
The onkeydown attribute fires when the user is pressing a key (on the keyboard).
For this, you have to import HostListener in your component ts file. import { HostListener } from '@angular/core'; then use below function anywhere in your component ts file. @HostListener('document:keyup', ['$event']) handleDeleteKeyboardEvent(event: KeyboardEvent) { if(event.
If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).
You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.
Example:
$(document).keydown(function(e) {
if(e.which == 98 && e.ctrlKey) {
// ctrl+b pressed
}
});
Why not use if
rather than switch
?
$(document).keydown(function(e) {
if ((e.keyCode === 37) || (e.keyCode === 39)) {
e.preventDefault();
alert("Arrow Key");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With