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?
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.
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.
The tab character can be inserted by holding the Alt and pressing 0 and 9 together.
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(); } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With