Skip to content

Tab key press event in JavaScript | Example code

  • by

Use the key event and Check if the key pressed is Tab (code = 9) to detect the Tab key press event in JavaScript.

Example handle the Tab keypress event in JavaScript

HTML example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    document.addEventListener('keydown', function(event)
    {
      var code = event.keyCode || event.which;
      if (code === 9) {  
        alert("Hello Tab key")
      }
    });
  </script>
</body>
</html>

Output:

Tab key press event in JavaScript

Q: How to call a function when pressing the tab key in JavaScript?

Answer: Add an event listener to the document and match the keycode with the tab keycode. If the condition is true then call function.

<!DOCTYPE html>
<html>
<body>

  <script>
    document.addEventListener('keydown', function(event) {
      if (event.which === 9) {
        hello();
     }
   });

    function hello(){
      alert("Hello function");
    }
  </script>
</body>
</html>

If you want to pass the field to the function, you could also add the event listener to the input itself. Then access it with event.target

Do comment if you have any doubts or suggestions on this JS event topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.