Tab key press event in JavaScript | Example code

Use key event and Check if the key pressed is Tab (code = 9) to detect 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 keycode with tab keycode. If condition 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 and 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

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