Categories
JavaScript Answers

How to handle Tab Key presses with JavaScript?

Spread the love

Sometimes, we want to handle Tab Key presses with JavaScript.

In this article, we’ll look at how to handle Tab Key presses with JavaScript.

How to handle Tab Key presses with JavaScript?

To handle Tab Key presses with JavaScript, we can listen for the keyup event.

For instance, we write:

<input /><input />

to add 2 input elements.

Then we write:

document.onkeyup = (e) => {
  if (e.keyCode === 9) {
    console.log("tab pressed");
  }
}

to listen to the keyup event emitted by anything on the page.

We check if the tab key is pressed by checking if e.keyCode returns 9.

Therefore, when we press tab to jump between the 2 inputs, we see 'tab pressed' logged.

Conclusion

To handle Tab Key presses with JavaScript, we can listen for the keyup event.

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 *