JQuery 'keypress' does not work for some keys in Chrome. How to work?

I am trying to implement a keystroke function that removes a div when the user presses Esc . This works for Firefox and IE with the following code:

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

If I press any key, the first alert displayed, and if I delete the Escape, the second alert displayed.

However, this does not work with Chrome. The first alert always displayed if I press any of the letter keys, but not when I press Escape, Tab, Space or any of the numbers.

Why was that? Is there a way to get Chrome to respond to these keystrokes?

+54
jquery google-chrome keypress
Oct 10 2018-10-10
source share
5 answers

Try using keydown .

+106
10 Oct 2018-10-10
source share

use keydown . keypress does not 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(); } }); 
+15
Mar 29 '11 at 10:26
source share

For the ESC key:

 $(document).keydown(function(e) { if(e.keyCode == 27) { /* Run code */ } } 

For letter keys such as "L":

 $(document).keypress(function(e) { if(e.which == 108) { } }); 

Works in both Chrome and Firefox

+2
Feb 04 '13 at 6:50
source share

After the second warning, add also

 e.preventDefault(); 

This will prevent the default event action from being triggered.

Read more about this method here.

Your code should look like

 $("body").keypress(function(e) { alert("any key pressed"); if (e.keyCode == 27) { alert("escape pressed"); e.preventDefault(); }}); 
+1
Nov 06 '12 at 10:32
source share

Using the jquery.hotkey js file, you can make the "Sort" button

 $(document).bind('keydown', 'esc', function(){ }); 
0
Dec 20 '16 at 6:30
source share



All Articles