Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's 'keypress' doesn't work for some keys in Chrome. How to work around?

I'm trying to implement key-press functionality which will remove a div when the user hits Esc. This works for Firefox & IE with the following code:

$("body").keypress(function(e) {     alert("any key pressed");     if (e.keyCode == 27) {         alert("escape pressed");     } }); 

If I hit any key, the first alert is displayed, and if I hit Escape, the second alert is also displayed.

This doesn't work with Chrome though. The first alert is always displayed if I hit any of the letter keys, but not when I hit Escape, Tab, Space or any of the numbers.

Why would this be? Is there any way to get Chrome to respond to these key presses?

like image 984
DaveDev Avatar asked Oct 10 '10 16:10

DaveDev


People also ask

Is jQuery keypress deprecated?

Probably false positive JS inspection: jQuery keyup(), keydown(), keypress() are marked as deprecated.

How does jQuery detect keyboard press?

jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.

What is the difference between jQuery Change () and keypress () events?

The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.

How do I know if Ctrl is pressed in jQuery?

You can easily detect the shift, alt and control keys from the event properties; $("button"). click(function(evt) { if (evt. ctrlKey) alert('Ctrl down'); if (evt.


2 Answers

Try handling keydown instead.

like image 92
SLaks Avatar answered Sep 28 '22 08:09

SLaks


use keydown. keypress doesn't work with ESC in Chrome (not sure about other browsers).

$(newTag).keydown(function(e) {  //keypress did not work with ESC;     if (event.which == '13') {       ProfilePage.saveNewTag(search_id, $(newTag).val());     }     else if (window.event.which){       $(newTag).remove();     } });  
like image 29
bear Avatar answered Sep 28 '22 08:09

bear