Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.
Notice: I'm taking a break from blogging to focus on Atari Gamer . com, check it out!

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
Something that really annoys me with the standard HTML textarea element is when the Tab key is pressed, focus is shifted to the next UI widget following the textarea. In my case I was using a textarea as input for editing formatted content to display on a web page (a lite CMS app essentially). I wanted to be able to insert tabs into content I was editing but didn't want to use a WYSIWYG text editor component.

This was my solution with jQuery...
$(document).delegate('textarea', 'keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
var start = this.selectionStart;
var end = this.selectionEnd;
var text = $(this).val();
var selText = text.substring(start, end);
text.substring(0, start) +
"\t" + selText.replace(/\n/g, "\n\t") +
this.selectionStart = this.selectionEnd = start + 1;

This code allows for tabs to be inserted between characters in the textarea like so...

It also works for inserting a tab at the start of the line...

Most importantly however, it works when selecting multiple lines and pressing Tab. Each of the lines is indented with a Tab character...


The code above intercepts Tab key presses for any textarea component. It then works out whether anything is selected and then inserts the Tab character into all of the appropriate spots. Once all the Tabs are inserted, the text cursor is set back to the beginning of the originally selected text.


Skip down to comments...
A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. If you spot something out of place, please do let me know.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...