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

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

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.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.