Kevin K
Kevin K

Reputation: 75

Textarea and tab keys: Get \t instead of jumping to the next element

I am using a html textarea called userInput but whenever I press tab it just moves to the next element. How would I make the tab key create a tab, or at least some spaces, and not move to the next element?

Upvotes: 2

Views: 193

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

Add an event listener for the keydown event, and prevent the event if it is a tab that've been pressed:

var ta = document.getElementById("ta");

ta.addEventListener("keydown", function(e) {                           // when a keydown happens
  if(e.keyCode === 9) {                                                // if the key that is pressed is a tab (keyCode 9)
    var start = this.selectionStart,                                   // get the selection start (or the cursor position if nothing is selected)
        end = this.selectionEnd,                                       // get the selection end (or the cursor position if nothing is selected)
        value = this.value;
    this.value = value.substr(0, start) + "\t" + value.substr(end);    // add a tab in-between instead of the selected text (or at cursor position if nothing is selected)
    this.selectionStart = this.selectionEnd = start + 1;               // set the cursor to one character after the last start index (right after the newly added tab character)
    e.preventDefault();                                                // IMPORTANT: prevent the default behavior of this event (jumps to the next element and give it focus)
  }
})
#ta {
  width: 100%;
  height: 170px;
}
<textarea id="ta"></textarea>

Upvotes: 2

Related Questions