Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle <tab> in textarea?

I would like a textarea that handles a situation of pressing tab key.

In default case if you press a tab key then focus leaves the textarea. But what about the situation when user wants to type tab key in textarea?

Can I catch this event and return focus to the textarea and add a tab to a current cursor position?

like image 696
sergzach Avatar asked May 26 '11 14:05

sergzach


People also ask

How do I get tabs to work in textarea?

Maybe use control + tab. This will highjack the browsers ability to other tabs(webpages), but users can just tab out of the textbox and then control tab to the other page. Should have a hint on the page use ctrl + tab for tab.

How many spaces is a tab?

Generally, a tab is the same width as 4 to 5 spaces provided the font being used equally sizes each character. For example, the Courier font's tab equals 5 spaces, whereas the Arial font is 11 spaces to each tab when the font size for both is set to 12.

How do you add a tab in HTML?

The tab character can be inserted by holding the Alt and pressing 0 and 9 together.


2 Answers

You can: http://jsfiddle.net/sdDVf/8/.


$("textarea").keydown(function(e) {     if(e.keyCode === 9) { // tab was pressed         // get caret position/selection         var start = this.selectionStart;         var end = this.selectionEnd;          var $this = $(this);         var value = $this.val();          // set textarea value to: text before caret + tab + text after caret         $this.val(value.substring(0, start)                     + "\t"                     + value.substring(end));          // put caret at right position again (add one for the tab)         this.selectionStart = this.selectionEnd = start + 1;          // prevent the focus lose         e.preventDefault();     } }); 
like image 64
pimvdb Avatar answered Sep 22 '22 15:09

pimvdb


Here is a modified version of pimvdb's answer that doesn't need JQuery:

document.querySelector("textarea").addEventListener('keydown',function(e) {     if(e.keyCode === 9) { // tab was pressed         // get caret position/selection         var start = this.selectionStart;         var end = this.selectionEnd;          var target = e.target;         var value = target.value;          // set textarea value to: text before caret + tab + text after caret         target.value = value.substring(0, start)                     + "\t"                     + value.substring(end);          // put caret at right position again (add one for the tab)         this.selectionStart = this.selectionEnd = start + 1;          // prevent the focus lose         e.preventDefault();     } },false); 

I tested it in Firefox 21.0 and Chrome 27. Don't know if it works anywhere else.

like image 28
alexwells Avatar answered Sep 21 '22 15:09

alexwells