How to Detect and Handle Tab Key Presses in JavaScript

Alex Dulcianu Feb 02, 2024
How to Detect and Handle Tab Key Presses in JavaScript

JavaScript features a built-in method to detect keyboard keypresses and multiple ways to handle these events. You can set up event listeners throughout your code, which is a great way to ensure that the desired events only happen when the correct elements are selected.

That said, specific keyboard keys have predetermined functions in most browsers - and indeed on most operating systems. For example, using F1 in most browsers will open a help page, and the F5 key will refresh the current page.

The same is true for the Tab key, which is used to cycle through hyperlinks and text boxes in most browsers. However, you can still detect this event using JavaScript and perform specific actions whenever the Tab key is pressed. For example, you may want to do something with the selected hyperlink or even change the properties of the text input whenever a user switches to it using Tab.

Here is an example of how you can add an event listener for the Tab key:

Create an Event Listener to Detect When the Tab Key Is Pressed in JavaScript

<a href="https://www.delftstack.com/">Test Link 1</a>
<a href="https://www.delftstack.com/contact/">Test Link 2</a>
<a href="https://www.delftstack.com/about-us/">Test Link 3</a>
document.addEventListener('keyup', detectTabKey);

function detectTabKey(e) {
  if (e.keyCode == 9) {
    activeElem = document.activeElement;
    console.log(activeElem.href);
  }
}

Output:

"https://www.delftstack.com/"
"https://www.delftstack.com/contact/"
"https://www.delftstack.com/about-us/"

The JavaScript code above has two working parts:

  1. The document.addEventListener() method takes two arguments: the kind of event you want to listen for (in this case, it is the keyup event), and the function you use want to execute when the event is triggered.
  2. Our custom detectTabKey() function checks if the key code for the event is the same as the one for the Tab key. If it is a match, print the hyperlink to the console.

Add More Logic to Ensure Only <a> Elements Trigger the Event Listener

Some of you may have already spotted an issue with the previous method: What happens if our webpage has input text boxes? If that is the case, pressing the Tab key will also cycle through them, and since they have no href attribute, our function will not work as intended.

Thankfully, JavaScript will not throw an error if that’s the case, but it will print out undefined whenever a text input is selected. To ensure that doesn’t happen, we need to add a step into our detectTabKey() function.

Let’s add a new element into our HTML code:

<a href="https://www.delftstack.com/">Test Link 1</a>
<a href="https://www.delftstack.com/contact/">Test Link 2</a>
<a href="https://www.delftstack.com/about-us/">Test Link 3</a>

<input type="text" placeholder="Text Box">

If we keep the same JavaScript code as before, the output will look like this:

Output:

"https://www.delftstack.com/"
"https://www.delftstack.com/contact/"
"https://www.delftstack.com/about-us/"
undefined

In order to fix this, we need to add another if statement into our detectTabKey() function. Here is the final code:

document.addEventListener('keyup', detectTabKey);

function detectTabKey(e) {
  if (e.keyCode == 9) {
    activeElem = document.activeElement;
    if (activeElem.tagName.toLowerCase() == 'a') {
      console.log(activeElem.href);
    }
  }
}

Output:

"https://www.delftstack.com/"
"https://www.delftstack.com/contact/"
"https://www.delftstack.com/about-us/"

The text box does not trigger our function even when selected as the active element since it does not meet the new condition. As such, the code will only print out the href attribute if the currently active element has the a tag attached to it. We also added the .toLowerCase() method to ensure we don’t miss any element.

Related Article - JavaScript Event