I would like to find out what character key is pressed in a cross-browser compatible way in pure Javascript.
"Clear" JavaScript:
function myKeyPress(e){
var keynum;
if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
}
<input type="text" onkeypress="return myKeyPress(event)" />
JQuery:
$("input").keypress(function(event){
alert(String.fromCharCode(event.which));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
keypress
event, which gives you a character code, rather than keyup
or keydown
which give you a key code. –
Hick e.which
is deprecated. Use e.key
instead, as in if(e.key == 'z')
–
Dodge e.key
still doesn't have full browser support. –
Argolis keyCode
for ArrowLeft
is 37, which is %
symbol. So this conversion doesn't seem to be fully reliable –
Prescription More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (
.keyCode
and.which
) are Deprecated.
node.addEventListener('keydown', function(event) {
const key = event.key; // "a", "1", "Shift", etc.
});
If you want to make sure only single characters are entered, check key.length === 1
, or that it is one of the characters you expect.
There are a million duplicates of this question on here, but here goes again anyway:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
The best reference on key events I've seen is http://unixpapa.com/js/key.html.
Copy-paste this into your address-bar:
data:text/html,<body style=font:12vw' onkeyup="this.innerHTML=['key','keyCode','code'].map(k=>k+': '+event[k]).join`<br>`">Press a key
This is just 134 bytes of code to produce the key
, keyCode
, and code
of the key you've just pressed. You can also save this as a bookmark so you can run it anytime.
<body style=font:8vw'
onkeyup="this.innerHTML=['key','keyCode','code'].map(k=>k+': '+event[k]).join`<br>`"
>Press a key
This works in "Run code snippet" as well.
Use this one:
function onKeyPress(evt){
evt = (evt) ? evt : (window.event) ? event : null;
if (evt)
{
var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
if (charCode == 13)
alert('User pressed Enter');
}
}
**check this out**
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).keypress(function(e)
{
var keynum;
if(window.event)
{ // IE
keynum = e.keyCode;
}
else if(e.which)
{
// Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
var unicode=e.keyCode? e.keyCode : e.charCode;
alert(unicode);
});
});
</script>
</head>
<body>
<input type="text"></input>
</body>
</html>
Detecting Keyboard press in JavaScript:
document.addEventListener(
"keydown",
function(event) {
console.log(event.key);
},
);
One of my favorite libraries to do this in a sophisticated way is Mousetrap.
It comes stocked with a variety of plugins, one of which is the record
plugin which can identify a sequence of keys pressed.
Example:
<script>
function recordSequence() {
Mousetrap.record(function(sequence) {
// sequence is an array like ['ctrl+k', 'c']
alert('You pressed: ' + sequence.join(' '));
});
}
</script>
<button onclick="recordSequence()">Record</button>
BH
If you're trying to get the value in client side JavaScript via the DOM, then a reliable alternative I've found is to make an invisible <input>
element, with an absolute position and (almost) no width, positioned underneath wherever you're typing, then when the user clicks or sets focus to whatever they're supposed to type on, call the focus()
function on the input, and use the result from the oninput
event to get the string entered into the input, and then get the first character from that string, or loop through it
(And make some exceptions for shift keys etc)
Then at the end of every event simply reset the value
of the input to an empty string
keydown
listener to document
without needing to create an extra input element. This answer adds very little to the existing ones. –
Aguilar document.onkeypress = function(event){
alert(event.key)
}
© 2022 - 2024 — McMap. All rights reserved.
event.key
will directly give you the pressed char – Holst