Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listener the keyboard type text in Javascript?

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?

like image 686
Tattat Avatar asked Dec 06 '10 15:12

Tattat


People also ask

How do you use keystrokes in JavaScript?

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.

Which event captures a keypress in JavaScript?

The onkeypress event occurs when the user presses a key (on the keyboard).

What is keyboard event in JavaScript?

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.

When you trigger a key in a keyboard What value does it return?

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.


1 Answers

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

like image 104
Tim Down Avatar answered Nov 07 '22 09:11

Tim Down