Skip to content

JavaScript tab key code | Handling Tab Keypress example

  • by

JavaScript tab key code is 9. Use the keydown event to get the tab key code or char code in JavaScript.

Detect tab key and code example

HTML example code, Capturing TAB key in JS. After launching coding press a tab key until the main window is in focus.

<!DOCTYPE html>
<html>
<body>

  <script>
    
    window.addEventListener('keydown', function(event) {
      const key = event.key;
      alert(key);
    });
  </script>

</body>
</html>

Output:

JavaScript tab key code

Q: How to detect “tab keypress” when the focus is on a button using JavaScript?

Answer: Use the below code with trans-browser compatibility. Detect the tab keypress on a button and focus on the specified textbox when the tab is pressed.

<!DOCTYPE html>
<html>
<body>
  <input ID="btnClear" onkeydown="return goToFirst();"/> 
  <button>Click...</button> <br>
  <input id="txtFirstName" type="text">

  <script>
    function goToFirst(evt) {
      var e = event || evt; 
      var charCode = e.which || e.keyCode;

      console.log(charCode);
      if (charCode == 9 ) {
        document.getElementById('txtFirstName').focus();
        document.getElementById('txtFirstName').select();
      }

      return false;
    };
  </script>

</body>
</html>

Output: By default, the focus should be on the button.

Handling Tab Keypress example

Do comment if you have any doubts or suggestions on this JS keycode 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