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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading