The use of keyboard shortcuts in web applications are often needed by the user. Javascript can handle keyboard event functions, so developers can use it well. On jQuery, a plugin named hotkeys.js can easily add a handler for the keyboard events with a lot of combinations.
Supported by technology and hardware that is getting better, the use of jquery will not burden the system browser in client side again. The use of jQuery hotkeys plugin will save your time in create the keyboard events in javascript.
If without the plugin, the use of keyboard codes javascript like the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var isCtrl = false; document.onkeyup=function(e){ if(e.which == 17) { isCtrl=false; } } document.onkeydown=function(e){ if(e.which == 17) isCtrl=true; if(e.which == 83 && isCtrl == true) { alert('test 1 2 3 4 5 6 .....'); return false; } } |
Please try by pressing “ctrl+s” on a web page browser, what happens?
Without jQuery plugin, you can run the javascript hotkeys. But you have to know the keyboard codes reference, below the following list of keycode in javascript
Of course using Hotkeys jquery plugins will be faster in writing code.
Table of Contents
JQuery Hotkeys Plugin
According to the official website of jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.
The use of this plugin is quite simple:
1 2 3 | $('input.foo').bind('keydown', 'F9', function(){ alert("this is F9"); }); |
But I am a little having problems when using ctrl + s on hotkeys plugin. When the input field get focus, keyboard event ctrl + s can not be run properly. Maybe I’m not good to applying them. So using javascript to handle this problem in the following ways
1 2 3 4 5 6 7 8 | $(document).keydown(function(event) { if((event.ctrlKey || event.metaKey) && event.which == 83) { alert("hello this is ctrl+s trigger"); event.preventDefault(); return false; }; } ); |
Maybe anyone can help me?
If you would like to see an example of the use of hotkeys plugin in full please visit JQuery hotkeys example.
There are some important things to note about how to implement a keyboard event handler in the web application.
- Avoid defining keyboard shortcut that has been provided by the browser, for example Ctrl + P to print.
- Use keywords that are rarely used as F1 – F9.
- Use the keyboard event handler wisely ,please do not confuse the user
Leave a Reply