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

7

I have a <textarea> that will work as a small source editor. I wanted you to press Tab to include a indentation in the text instead of focusing on the next element, which is the default behavior for the key. I wanted it to be possible to write the formatted text in the database, and when I uploaded it back to <textarea> , I would show the indented inserts.

    
asked by anonymous 15.12.2014 / 16:03

2 answers

7

Only intercept keydown when 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'llprobablyneedapolyfill> like this to make the crossbrowser response code, since in some versions of IE the text selection is treated differently.

    
15.12.2014 / 16:12
6

The keyCode of the TAB is 9. Add an event to the textarea, so when the user types TAB, it inserts a \t in the current position of the cursor:

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>
    
15.12.2014 / 16:37