How to include a indent when using the tab key in a textarea?

Asked

Viewed 863 times

7

I have a <textarea> which will act as a small source editor.
I wish that, by pressing the Tab, include a indent in the text instead of focusing on the next element, which is the default behavior of the key.
I wanted it to be possible to save the formatted text to the database, and by uploading it back to the <textarea>, shows the indentations inserted.

2 answers

7


You just intercept the keydown when the keyCode === 9

$('textarea').bind('keydown', function(e) {
    if(e.keyCode === 9) {
        e.preventDefault();
        var inicioDaSelecao = this.selectionStart,
            fimDaSelecao = this.selectionEnd,
            recuo = '\t'; //Experimente também com '    '
      
        this.value = [
            this.value.substring(0, inicioDaSelecao),
            recuo,
            this.value.substring(fimDaSelecao)
        ].join('');

        this.selectionEnd = inicioDaSelecao + recuo.length; 
    }    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>

You will probably need a polyfill like this to make the response code crossbrowser, since in some versions of IE the text selection is treated differently.

6

The keyCode of the TAB is 9. Add an event to the textarea, so when the user type TAB, he insert a \t at the current cursor position:

document.getElementById('textedit').addEventListener('keydown', function(e) {
    if(e.keyCode === 9) { // TAB
        var posAnterior = this.selectionStart;
        var posPosterior = this.selectionEnd;

        e.target.value = e.target.value.substring(0, posAnterior)
                         + '\t'
                         + e.target.value.substring(posPosterior);

        this.selectionStart = posAnterior + 1;
        this.selectionEnd = posAnterior + 1;
 
        // não move pro próximo elemento
        e.preventDefault();
    }
}, false);
<textarea id="textedit"></textarea>

<p>
  Próximo input:<br>
  <input type="text" id="" />
</p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.