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

I have an HTML link and I want to take some action when the user leaves it, but only if the user moves forward through the document and not backward.

Is there a reliable cross-browser way to determine how a user navigates a document, or is it really, if at all, tabooing a document? I am attached to the blur event, but this does not necessarily mean that the user is tabbing.

I looked at checking the value of document.activeElement or the hasFocus attribute of a previous custom item in the source, but:

  • this is similar to relatively recent additions and therefore may not be widely supported, and
  • I am not sure that they will be checked when the blur event occurs, since even if the user is tabbing, I do not think that the next element will be focused.
+6
source share
2 answers

You will have to handle the keydown event in 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 out this JSFiddle example , which defines forward and backward tabs from a specific link.

Sidenote You didn't include the jQuery tag in your al question, although I provided jQuery code in your answer. Since you have Javascript as well as jQuery badges, I suppose it will be trivial for you to convert my code into pure Javascript.

+6
source

As an alternative to a good solution from Robert, maybe you can use the tabindex attribute? Set it for your html links and other tabbable elements. Then check it out in javascript.

Solution with tabindex: jsfiddle

Side effect . Elements will also respond to mouse clicks. They will behave correctly. Thus, it can be a good side effect or a bad side effect depending on your needs.

+1
source

Source: https://habr.com/ru/post/889098/


All Articles