« Blocking certain sites from hotlinking images via mod_rewrite | Home | Using pattern lists in Unix »
Rewind caret in a non-empty <textarea>
When you TAB into a non-empty <textarea> the caret is usually placed after the last character. Which is not always ok. This JavaScript code deals with this problem for all modern browsers. IE variant needs onfocus and onbeforedeactivate event handlers which are installed with add_handler() function.
function add_handler(element, event_type, func) {
if (element.attachEvent) { // IE
element.attachEvent('on' + event_type, func);
} else if (element.addEventListener) { // W3C
element.addEventListener(event_type, func, false);
} else { // should not happen
element['on' + event_type] = func;
}
}
function rewind_caret(input) {
if (input.createTextRange && typeof input.caret_pos == 'undefined') {
add_handler(input, 'focus', function () {
var range;
if (typeof input.caret_pos == 'undefined') {
range = input.createTextRange();
range.collapse(true);
range.moveStart('character', input.caret_pos);
} else {
range = input.caret_pos;
}
range.select();
return true;
});
add_handler(input, 'beforedeactivate', function () {
input.caret_pos = document.selection.createRange().duplicate();
});
} else if (input.setSelectionRange) {
input.setSelectionRange(0, 0);
}
}
Topics: javascript | Submitter: kappa
4 Responses to “Rewind caret in a non-empty <textarea>”
Comments
You must be logged in to post a comment.
February 19th, 2006 at 2:07 am
It was really hard to write this post.
How is one supposed to post code snippets into this WordPress? The post editor eats identations, linebreaks, does not allow inline <code> elements and does lots of other nasty things to code.
February 19th, 2006 at 3:28 pm
Putting the code and /code tags around everything should've worked, no?
February 19th, 2006 at 8:40 pm
No, I tried. <code> does not save identation.
February 19th, 2006 at 8:41 pm
BTW, thanks for adding "javascript" category!