Capture tab key press with Javascript

Posted on 17-02-2013 21:51 by graham
This tutorial shows how to capture the event when the tab key is pressed by a user.

Detecting the key press

The tab character has key code = 9. In our code we need to check the key code of every character corresponding to the pressed key, and react to it properly when the key code is 9.

The code below fires a check every time a key is pressed on a text area and if the key code represents the tab character, it inserts an actual tab character into the text area, instead of switching to the next item in the tab order, which is the default tab behaviour.
$('textarea').keydown(function(e) {
var keyCode = e.keyCode || e.which;

if (keyCode == 9) {
$(this).val($(this).val() + '\t');

See demo in our code sandbox.


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems