How to Make the Tab Key Indent Text in a Texarea

I recently had a situation where the user needed to be able to insert tabs into a texarea. Normally, when the cursor is inside of a textarea, pressing tab will move the cursor to the next field or button in the form. However, in this case, I needed to change that behavior and make the tab key insert a tab character into the textarea content instead. Here’s how I did it in raw Javascript, no jQuery needed.

Note: Doing this will break the accessibility of your page in a very bad way. Make sure you have a Very Good Reason to do this before implementing it, as it will make it impossible for users to tab out of the textarea.

 * Hijack the tab key to insert the tab into the content rather than moving the cursor to the next field or button in
 * the form.
document.getElementById( 'my-texarea' ).addEventListener( 'keydown', function( event ) {

    if ( event.keyCode === 9 ) {

        // Set up some variables. We need to know the current position of the cursor or selection.
        var selectionStartPos = this.selectionStart;
        var selectionEndPos   = this.selectionEnd;
        var oldContent        = this.value;

        // Set the new content.
        this.value = oldContent.substring( 0, selectionStartPos ) + "\t" + oldContent.substring( selectionEndPos );

        // Set the new cursor position (current position + 1 to account for the new tab character).
        this.selectionStart = this.selectionEnd = selectionStartPos + 1;

        // Prevent the default action (tabbing to the next field or control).

Note: You will want to make sure this code runs after the DOM has been loaded, or it will not be able to access your textarea.

Leave a Reply

Your email address will not be published. Required fields are marked *