Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock tab key with javascript?

How to lock or disable and again the tab key with javascript?

like image 285
PsyGnosis Avatar asked May 03 '11 15:05

PsyGnosis


3 Answers

$(document).keydown(function(objEvent) {
    if (objEvent.keyCode == 9) {  //tab pressed
        objEvent.preventDefault(); // stops its action
    }
})
like image 65
Naftali Avatar answered Oct 19 '22 19:10

Naftali


You can do it like this:

$(":input, a").attr("tabindex", "-1");

That will disable getting focus with tab in all links and form elements.

Hope this helps

like image 13
Edgar Villegas Alvarado Avatar answered Oct 19 '22 19:10

Edgar Villegas Alvarado


Expanding on Naftali aka Neal's answer, here's how you'd do it with vanilla JS and both start and stop Tab behavior buttons:

let stopTabFunction = function(e) {
  if (e.keyCode == 9) {
    e.preventDefault();
  }
};
document.getElementById('stopTabButton').onclick = function() {
  document.addEventListener('keydown', stopTabFunction);
};
document.getElementById('resumeTabButton').onclick = function() {
  document.removeEventListener('keydown', stopTabFunction);
};
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<br/><br/>
<input type="button" id="stopTabButton" value="Stop Tab!"/>
<input type="button" id="resumeTabButton" value="Resume Tab!"/>

Note that this also works for Shift + Tab (reverse direction).

JSFiddle


However, in my case, I wanted slightly different behavior: I wanted to basically lock down Tab focus to a single div. To do this, I placed a div before and after it, gave them both tabindex="0" (document-defined tab order on the div's themselves), to make the outer edges of the div focusable, like so:

<div id="beforeMyDiv"></div>
<div id="myDiv">
  <!-- Only want Tab indexing to occur in here! -->
</div>
<div id="afterMyDiv"></div>

Then, I changed the function from earlier to this:

//Get the div's into variables etc.
//...

let forceTabFocusFunction = function (e) {
    if (e.keyCode == 9) {
        //Force focus onto the div.
        if (!myDiv.contains(document.activeElement)) {
            if (e.shiftKey) {
                afterMyDiv.focus();
            } else {
                beforeMyDiv.focus();
            }
        }
    }
};

That did the trick nicely.

like image 3
Andrew Avatar answered Oct 19 '22 18:10

Andrew