Categories
JavaScript Answers

How to Detect Focus Initiated by Tab Key with JavaScript?

Spread the love

Sometimes, we want to detect focus initiated by tab key with JavaScript.

In this article, we’ll look at how to detect focus initiated by tab key with JavaScript.

Detect Focus Initiated by Tab Key with JavaScript

To detect focus initiated by tab key with JavaScript, we can listen to the keyup event.

And if the keyup event is triggered by a tab key and the input is focused, then we know the focus is triggered by the tab key.

For instance, we can write:

<input type="text" id="foo" />  
<input type="text" id="detect" />

to add the inputs.

Then we can detect whether the input with ID detect is focused by pressing the tab key by writing:

$(window).keyup((e) => {  
  const code = (e.keyCode ? e.keyCode : e.which);  
  if (code === 9 && $('#detect:focus').length) {  
    console.log('I was tabbed!');  
  }  
});

We call keyup on window with an event listener.

In the event listener, we check if the keyCode is 9, which is the key code for the tab key.

And we also check if there’s an element with ID detect that is focused with $(‘#detect:focus’).length .

If both are true , then we know it was focused by pressing tab.

Conclusion

To detect focus initiated by tab key with JavaScript, we can listen to the keyup event.

And if the keyup event is triggered by a tab key and the input is focused, then we know the focus is triggered by the tab key.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *