Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript, how can you tell if a user is tabbing backwards?

I've got an HTML link, and I want to take some action when the user tabs away from it - but only if the user is tabbing forwards through the document, as opposed to backwards.

Is there a reliable cross-browser way to detect which way the user is tabbing through the document, or indeed if they're tabbing through the document at all? I'm binding to the blur event, but that doesn't necessarily mean that the user is tabbing.

I've had a look at inspecting the value of document.activeElement, or the hasFocus attribute of the previous focusable element in the source, but:

  1. those seem like relatively recent additions, and thus might not be widely supported, and
  2. I'm not sure they'll be inspectable when the blur event fires, as even if the user is tabbing, I don't think the next element will be focused yet.
like image 993
Paul D. Waite Avatar asked May 26 '11 11:05

Paul D. Waite


People also ask

How to tab backwards JavaScript?

// Reverse tabbing (Key: Shift+Tab).

When you press a tab does it go backwards?

Shift+tab should do the trick. It also works in Alt-tab to cycle backwards through tabs. Also, in Firefox, you can press Ctrl+tab to cycle through tabs.

How does tab work in JavaScript?

In the web page tab key works as an html element navigator, which means if you push the tab key button, it moves current element focus to the next element.

How do you know when a tab has changed?

Detect tab changes with JavaScript To detect the tab change we use pure JavaScript without jQuery etc. Everything you need is hidden in this code. We register the blur event on the global document variable. Generally, the blur and focus events are often used in conjunction.


1 Answers

You will have to handle keydown event on the link itself.

$("your link selector").keydown(function(evt){
    if (evt.which === 9)
    {
        if(evt.shiftKey === true)
        {
            // user is tabbing backward
        }
        else
        {
            // User is tabbing forward
        }
    }
});

Check this JSFiddle example that detects forward and backward tabbing on a particular link.

Sidenote: You didn't specify jQuery tag on your question al though I provided jQuery code in my answer. Since you hold Javascript as well as jQuery badges I suppose it's going to be trivial for you to convert my code to pure Javascript.

like image 75
Robert Koritnik Avatar answered Oct 30 '22 18:10

Robert Koritnik