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:
blur
event fires, as even if the user is tabbing, I don't think the next element will be focused yet.// Reverse tabbing (Key: Shift+Tab).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With