Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting text at cursor in a textarea, with Javascript

I've had a look round the web for solutions, and there are some, but they all seem to split code into supporting IE and Firefox.

I was wondering if there's a more elegant way which would work on every browser, to insert some text at the cursor in a textarea.

Thanks very much.

like image 859
richw81 Avatar asked Jul 22 '10 11:07

richw81


1 Answers

No, there isn't. IE has its TextRange objects to do the job. IE >= 9 and everything else for the last long time has selectionStart and selectionEnd properties on textareas and text inputs. This particular task isn't too bad: the following will delete the current selection (if one exists), insert text at the caret and reposition the caret immediately after the inserted text, in all the major browsers:

function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}
like image 180
Tim Down Avatar answered Sep 21 '22 20:09

Tim Down