Note: This is a mirror of http://teddevito.com/demos/textarea.html as of 2011-04-04.
This is a demo of the "Tabby" Javascript jQuery plugin to use tabs in regular textareas to make them suitable for in-browser coding of languages like HTML, CSS, Javascript, or your favorite server-side language. The idea is to be able to use a press of the TAB button or SHIFT+TAB to indent or outdent your code.
Simply use TAB to indent code in the textarea, SHIFT+TAB to outdent. It works on a single line or over a range of lines.
Browsers use the TAB keypress as a page control. Consequently, when you hit TAB, focus leaves the textarea and moves to the next available field.
First, let me distinguish this solution. There are a lot of results for the Google search "tabs in textarea" and there were 3 common issues relating to the fulfillment of the concept of this script (I'm sure each solution was completely adequate for it's author, but not for this concept!).
\t
First, when an activated textarea has focus, we'll need to capture the keypress event and note when either SHIFT or TAB have been pressed.
Then, we'll do some simple processing to figure out whether we're dealing with a selected range or not and add/remove the appropriate tabs.
To prevent focus from leaving the textarea when we're done adding/removing tabs, we'll return false through the event we bind to each textarea to stop the event from bubbling up. There is also a lightweight workaround for Opera you'll notice that has to restore focus after Opera takes it away.
There are two main parts to the code: the gecko version and the IE version. While IE is simpler for tabbing when the user has not selected any text, it is very complex for selections. You'll notice there are a bunch of ranges that are used to establish the correct length and positioning before any tabs get added or removed.
Very simple. Just call the plugin on your textareas.
jQuery(document).ready(function () {
$("textarea").tabby();
});
The plugin is setup so you can pass an argument for the tab string that gets used, but it's really just there to allow future development of that feature if it becomes important. For now it is really just a hook, as you can find in the code if you're so inclined.
Just one right now:
version 0.11
Chrome 1.0, FF 3.0, IE 6 & 7, Safari 3.2, Opera 9.6
As the biggest challenge was handling the idiosyncrasies in MSIE's TextRanges, the most helpful resource on this project was the Microsoft Developer Network reference. Look for anything that relates to the TextRange Object. The list on the left contains all the methods you will see used in my code. Just click around to look them all up.
Various similar solutions, explanations and resources:
someRange.text
trims \r\n
and the move
methods all handle \r\n
as a single character.