Manage JavaScript hotkeys in Chrome browser

I have the following jQuery code on a site that I built:

$(document).ready(function() { // Other Bindings/Initializations Removed // Hotkey Event Handler to 'doSomething' //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- $(document).keypress("a",function(e) { if(e.altKey) { // Doesn't work doSomething(); } }); // Hotkey Event Handler to 'doSomething' //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- $(document).keypress("a",function(e) { if(e.shiftKey) { //Works as Expected? doSomething(); } }); }); 

The code catches the events of the key combination, in this case "Alt-A", and then proceeds to calling the function that performs the corresponding action. I tested this function in FireFox, and the function was called as expected. When I tested this feature in Chrome, the function was not called, but instead an unpleasant beep was called. I thought that perhaps β€œAlt-A” came across an important combination of browser hotkeys, so β€œA” changed to β€œN”, β€œG”, and then β€œK”; every time a function was not called and an error signal was emitted. However, when I created the Shift-A / N / G / K hotkey combination, Chrome called the function expected.

  • Why does Chrome handle the Alt key differently?

  • How to define a hotkey for my site so that it works in Chrome using the "Alt" key?

+2
source share
2 answers

This works in Chrome and Firefox, however in IE Alt + a the favorites menu opens. I do not know how you would do it.

Fiddle

HTML:

 <a accesskey="a">​ 

JavaScript:

 $(document).ready(function() { // Other Bindings/Initializations Removed // Hotkey Event Handler to 'doSomething' //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- $(document).keypress("a", function(e) { if (e.shiftKey) { //Works as Expected? alert("shift a"); } if (e.altKey) { alt_a_function(); } }); $(document).on("click", "[accesskey=a]", function() { alt_a_function(); }); }); function alt_a_function() { alert("alt a"); }​ 
+2
source

The jQuery docs say the first argument . keypress () is the "Map of the data to be passed to the event handler." "Perhaps jQuery is confused when this object is a string, which causes an error in Chrome.

To verify a specific key in an event handler, use e.which to get the character code.

0
source

All Articles