No, there isn't. IE has its appalling TextRange
objects to do the job. 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 insert text at the end of the selection 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, endIndex) + 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();
}
}