I’m working on a project where I have a button which starts some processing when pressed and wanted to add a keyboard shortcut (Ctrl-E) to also trigger this processing.
The processing on click is handled like this:
$("#evaluate").click(function () { ... });
Now I first implemented the keyboard shortcut using a keypressed event:
$(document).bind('keypressed', function (event) { if (event.ctrlKey || event.metaKey) { switch (String.fromCharCode(event.which).toLowerCase()) { case 'e': $("#evaluate").click(); return false; } } });
Unfortunately, this does work in Firefox but not in Internet Explorer (the click is not triggered). For it to work in Internet Explorer, you need to use keydown instead of keypressed. So I changed it to look like this:
$(document).bind('keydown', function (event) { if (event.ctrlKey || event.metaKey) { switch (String.fromCharCode(event.which).toLowerCase()) { case 'e': $("#evaluate").click(); return false; } } });
Now it works in IE and Firefox. The only problem left was that in Firefox, the event is further propagated. In this case, the search box is activated.
I first thought I needed to add an event.preventDefault() and/or event.stopPropagation() but it didn’t help. The trick is actually to add a keypressed event handler which will return false if Ctrl-E is pressed:
$(document).bind('keydown', function (event) { if (event.ctrlKey || event.metaKey) { switch (String.fromCharCode(event.which).toLowerCase()) { case 'e': $("#evaluate").click(); return false; } } }); $(document).bind('keypressed', function (event) { if (event.ctrlKey || event.metaKey) { switch (String.fromCharCode(event.which).toLowerCase()) { case 'e': return false; } } });
Now it works in both IE and Firefox !