I am trying to alert the key which was pressed on both PC and mobile devices. However, on mobile devices, it returns the value “Unidentified”. Why is that?
$(document).on("keydown", function(e) {
alert(e.key);
});
I am trying to alert the key which was pressed on both PC and mobile devices. However, on mobile devices, it returns the value “Unidentified”. Why is that?
$(document).on("keydown", function(e) {
alert(e.key);
});
On mobile devices, the keydown
event does not provide the key
property. Instead, you can use the keyCode
or which
property to get the code of the key that was pressed.
Here is an updated code snippet that should work on both PC and mobile devices:
$(document).on("keydown", function(e) {
alert(e.key || String.fromCharCode(e.keyCode || e.which));
});
This code first tries to get the key
property, and if that is not available (i.e., on mobile devices), it uses the keyCode
or which
property and converts it into a character using String.fromCharCode()
.