开发者

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

开发者 https://www.devze.com 2023-03-08 07:40 出处:网络
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 tabbi开发者_开发知识库ng forwards through the document, as opposed to 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 tabbi开发者_开发知识库ng 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.


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.


As an alternative to a good solution from Robert, maybe you can leverage tabindex attribute? Set it for your html links and other “tabbable” items. Then check it in javascript.

Solution with tabindex: jsfiddle

Side effect: Elements will also react on mouse clicks. They will behave correctly. So this might be a good side effect or bad side effect depending on your needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消