Many a times we end up in situations where in our clients are windows app migrants to web. And they could not let go off the “hotkey” concept. Let’s say “Ctrl + S” or “Alt + R” to perform save or submit operation on a website. The options are endless.
A scalable code that you could use to achieve something in line with this is given below:
//Register the Utility Namespace var Utility = Utility || {}; /** * @MethodName : Utility.RegisterKeyPress * @Description : Register multiple key press events * @Param {object} ctrl : The control to be clicked when the user press Alt + R * * @Example : Utility.RegisterKeyPress('#btnSubmit'); */ Utility.RegisterKeyPress = function (ctrl) { //keyCodes for Alt(18) and r(82) var codeset = { 82: false, 18: false }; //Tracking the Key down & Key up events $(document).on('keydown', function (e) { if (e.keyCode in codeset) { codeset[e.keyCode] = true; if (codeset[82] && codeset[18]) { //Functionality to be executed on key press - Alt + R //An alert here would trigger on each key press //Instead define your functionality here //Click is an example used here. $(ctrl).click(); } } }).on('keyup', function (e) { if (e.keyCode in codeset) { codeset[e.keyCode] = false; } }); }; //Invoke the above method //When the user press Alt + R on the page, it will trigger the submit button click Utility.RegisterKeyPress('#btnSubmit');
You could extend this code to any key press by referring to the javascript keycode chart from here.
Hope this was useful!!
Amazing! Its really awesome article, I have got much clear idea regarding from
this post.
I just like the helpful info you provide in your articles.
I’ll bookmark your blog and test once more here regularly. I’m slightly certain I’ll be told many new stuff right here! Best of luck for the next!
Thanks, Although I did not do it this way but this gave me a clue, check out my code in jquery below: trying to detect ctrl+e and make sure it is pressed at the same time to remove a div called drag_box
var ctrl = {224 : false, 69:false}
$(window).keyup(function(e) {
ctrl = {224 : false, 69:false}
})
$(window).keydown(function(e) {
if (e.keyCode in ctrl) {
ctrl[e.keyCode] = true;
}
if (ctrl[224] && ctrl[69]) {
$(“#drag_box”).remove();
ctrl = {224 : false, 69:false}
}
})