I have the following code:
$('.field').keypress(function(event) {
if (event.keyCode == 27) alert(event.keyCode);
});
I need to catch "Escape" pressing and do some actions. But now it code does't work. I have tried to use this code:
$('.field').keypress(function(event) {
alert(event.keyCode);
});
I was pressing by Escape button, but it didn't work (I haven't seen any alerts). Please, tell me, how can I fix it?
I have the following code:
$('.field').keypress(function(event) {
if (event.keyCode == 27) alert(event.keyCode);
});
I need to catch "Escape" pressing and do some actions. But now it code does't work. I have tried to use this code:
$('.field').keypress(function(event) {
alert(event.keyCode);
});
I was pressing by Escape button, but it didn't work (I haven't seen any alerts). Please, tell me, how can I fix it?
Share Improve this question edited Jul 19, 2012 at 13:24 Esailija 140k23 gold badges279 silver badges328 bronze badges asked Jul 19, 2012 at 13:19 user1538002user1538002 571 silver badge5 bronze badges 2-
1
jQuery normalises the
keyCode
in theevent.which
property. It's not an answer and won't solve the problem but just a tip – Esailija Commented Jul 19, 2012 at 13:25 -
@Esailija: Talk about learning something every day...I thought it was
keyCode
that jQuery normalized (fromwhich
as necessary), but the docs are clear it's the other way around. Thanks. – T.J. Crowder Commented Jul 19, 2012 at 13:40
1 Answer
Reset to default 10Use keydown
or keyup
rather than keypress
. keypress
only fires for keystrokes that result in characters, which (by convention) Esc doesn't (even though some charsets, such as ASCII, do have a character called "escape").
For more about handling keystrokes in JavaScript: JavaScript Madness: Keyboard Events