I am looking for a way to translate a keypress into the string corresponding to the chracter. Something like this:
$(document).keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
except that this code does not take into account capitalization and does not work for special character, e.g. “,”. This:
$(document).keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
seems to the trick, but it can not prevent default browser actions (such as go back on backspace) and there seem to be browser compatibly issues.
Is there any better way, that works across browsers and keyboard layouts ?
It’s not possible to reliably get the character from the
event.whichproperty at an event type other thankeypress.If you’re questioning that statement, use the demo at this page. The
event.whichproperty can only be translated correctly at akeypressevent.If you want to ignore capitals, use the
.toLowerCase()method.