Detect multiple key press in javascript for your website


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!!

Enable Tab navigation for your entire page using jQuery


One of the most commonly faced Accessibility issue is in maintaining the tab order. If you don’t take it the right way, you might end up wasting days and days of effort, when you can just get it done in 2mins using jQuery.

Requirement:

Clicking on tab should go through all the functional controls on my current page.

Solution:

$(function() {
SetTabIndex();//Set tabIndex for all the HTML input elements, dropdowns, anchor tags and any control with classname as ‘linkname’ coming under control with id ‘myId’
});
function SetTabIndex() {
var tabindex = 1;
$(‘input,select,a,#myId .linkname’).each(function() {
if (this.type != “hidden”) {
var $input = $(this);
       $input.attr(“tabindex”, tabindex);
tabindex++;
}
});
}

Concept:

It’s very simple, you just need to set the tabIndex property of all the desired controls on your page, when the DOM load is complete.

Word of Caution:

It might look simple to you, but there is an expensive for loop going on inside, hence its desirable to avoid using any classnames and good to target Ids and specific controls. But i did not see much impact on my page which had around 300 links.

Hope this saved your time and effort.