Reputation: 5488
I have the following jQuery code on a site 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 key-press combination events, in this case "Alt-A", and then proceeds to call a function which preforms the appropriate action. I tested this feature in FireFox and the function was called as expected. When I tested the feature in Chrome the function was not called and an obnoxious error tone was emitted instead. I thought that perhaps "Alt-A" collided with an important browser hotkey combination so changed "A" to "N", "G", and then "K"; each time the function was not called and the error tone was emitted. However when I created a Shift-A/N/G/K hotkey combination, Chrome called the function as expected.
Why does Chrome handle the "Alt" key differently?
How to I define a hotkey for my site so that it will work in Chrome using the "Alt" key?
Upvotes: 2
Views: 1381
Reputation: 12228
This works in Chrome and Firefox, however in IE Alt+a opens the favorites menu. I'm not sure how you would override that.
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");
}
Upvotes: 2
Reputation: 37761
The jQuery docs say that the first argument to .keypress() is "A map of data that will be passed to the event handler." Perhaps jQuery is confused when that object is a string, which causes an error in Chrome.
To check for a particular key in the event handler, use e.which
to get the character code instead.
Upvotes: 0