I want to get the keyboard typed text, not the key code. For example, I press shift+f, I get the "F", instead of listen to two key codes. Another example, I click F3, I input nothing. How can I know that in js?
To record a keypress event in JavaScript, use the code below: // Add event listener on keypress document. addEventListener('keypress', (event) => { var name = event. key; var code = event.
The onkeypress event occurs when the user presses a key (on the keyboard).
KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type ( keydown , keypress , or keyup ) identifies what kind of keyboard activity occurred.
The keyboard event object has two important properties: key and code properties that allow you to detect which key has been pressed. The key property returns the value of the key pressed while the code represents a physical key on the keyboard.
To do it document-wide, use the keypress
event as follows. No other currently widely supported key event will do:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
alert("Character typed: " + String.fromCharCode(charCode));
}
};
For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html
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