Circular Focus TAB and Shift+TAB using jQuery

Sometimes HTML pages having form fields need keyboard navigation by a user in a specific area or a container. A user can navigate using TAB forward motion or TAB+SHIFT key combination for backward navigation through form elements like the link, input, text areas, select dropdowns etc.

But we can control it to some extent using HTML attribute tabindex to set an order of navigation. After completing all elements it jumps to browser controls which annoys a user not interested in the focus of those controls.

Here we will discuss a JS code to loop a user in a specified container navigate focus on field controls using TAB or TAB+Shift combination of keys.

See Demo Here and try to use TAB(Forward motion) and TAB+Shift Keys(Backward motion)

In HTML we will define an order of focus using tabindex attribute

<div class="limitTablJolly">
    <a tabindex=1>link</a>    
     <a tabindex=2>link</a>    
     <a tabindex=3>link</a>    
     <a tabindex=4>link</a>    
     <a tabindex=5>link</a>    
     <a tabindex=6>link</a>    
     <a tabindex=7>link</a>    
     <a tabindex=8>link</a>    
     <a tabindex=9>link</a>    
     <a tabindex=10>link</a>   

In jQuery/ Javascript we will define loop handler as follow:

$(document).ready(function() {
    lastIndex = 0;
    $(document).keydown(function(e) {
        if (e.keyCode == 9) var thisTab = $(":focus").attr("tabindex");
        if (e.keyCode == 9) {
            if (e.shiftKey) {
                //Focus previous input
                if (thisTab == startIndex) {
                    $("." + tabLimitInID).find('[tabindex=' + lastIndex + ']').focus();
                    return false;
            } else {
                if (thisTab == lastIndex) {
                    $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
                    return false;
    var setTabindexLimit = function(x, fancyID) {
        startIndex = 1;
        lastIndex = x;
        tabLimitInID = fancyID;
        $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
    /*Taking last tabindex=10 */
    setTabindexLimit(10, "limitTablJolly");

This will create a TAB focus loop on the elements with tabindex inside the wrapper defined by selector class “limitTablJolly“Users can also move in reverse order by pressing the TAB+SHIFT keys on the webpage.


2 thoughts on “Circular Focus TAB and Shift+TAB using jQuery”

Leave a Comment

Your email address will not be published. Required fields are marked *