Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

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...
 JavaScript
$(document).delegate('textarea', 'keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var start = this.selectionStart;
var end = this.selectionEnd;
var text = $(this).val();
var selText = text.substring(start, end);
$(this).val(
text.substring(0, start) +
"\t" + selText.replace(/\n/g, "\n\t") +
text.substring(end)
);
this.selectionStart = this.selectionEnd = start + 1;
}
});


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


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


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

htmltexareatab_4.png


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.



-i

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...