Snippet JS to tabulate in textarea

Tabulate in a textarea It is an impossible task without the use of javascript, since the default behavior of this key in a web is to change the focus of a input to the next in a form. To achieve this goal I usually use the following function, which, using a class like query selector, allows tabulating in all textareas of a page.

Below you can see the snippet that watch the key press tab inside a textarea:

$('.tab-listener').keydown(function(e) {
 //para compatibilidad con navegadores recuperamos la tecla con keycode o which
  var keyCode = e.keyCode || e.which;

  if (keyCode == 9) { //código de la tecla tabular
  //recuperamos la posición del caracter en el que se situa el cursor
    var start = this.selectionStart;
    var end = this.selectionEnd;

    // componemos el contenido del texarea: texto anterior a la seleccion + tab + texto después de la selección
    $(this).val($(this).val().substring(0, start)
                + "\t"
                + $(this).val().substring(end));

    // volvemos a colocar el puntero dónde toca
    this.selectionStart = this.selectionEnd = start + 1;


  • how do we tab in the textarea with javascript?

how do we tab in the textarea with javascript?

Now I am going to explain the keys of this snippet:

  1. First you have to assign the function to the html event keydown for each of the textarea desired, this is essential to be able to check each of the keys that have been pressed in the text field in which it is written. It is important to highlight that I have used jQuery to assign the event.
  2. Secondly, it is important to point out that, in order to know that the tabular key has been pressed inside the text field, we must recover key codeand check that it is 9. We do this in lines 3 and 5.
  3. Once we know that the user has pressed the key tab in it textarea, we stop the default functionality of the event with e.preventDefault()thus we prevent the browser from jumping to the next field of the form.
  4. The next thing is to store the initial and final position of the user’s selection (lines 8 and 9) since it may have been simply positioned on a character or a text and tab selection may have been made.
  5. We add the character “\t”, which is in charge of tabulating in html, right in the middle of the user’s selection.
  6. Finally we have to leave the user cursor in the same position (start + 1).

Finally I leave you a demonstration in JSFiddle here.

Leave a Reply