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:
- those seem like relatively recent additions, and thus might not be widely supported, and
- I’m not sure they’ll be inspectable when the
blurevent fires, as even if the user is tabbing, I don’t think the next element will be focused yet.
You will have to handle
keydownevent on the link itself.Check this JSFiddle example that detects forward and backward tabbing on a particular link.