Search code examples
javascripttextarea

JavaScript setSelectionRange() method and cursor position


I have the following piece of JavaScript for dynamically inserting unicode characters - represented below by the txtToIns variable - into a body of text

elmt.value = elmt.value.substring(0, elmt.selectionStart) + txtToIns + " " + elmt.value.substring(elmt.selectionStart, elmt.selectionEnd) + elmt.value.substring(elmt.selectionEnd, elmt.value.length) + " ";
elmt.focus();
elmt.value = elmt.value.trim();

With the above the cursor is always at the end of the text. Is there any way I can place it directly after txtToIns? And no, txtToIns.focus() won't work


Solution

  • I'm not sure what you're trying to do with the space characters in the textarea value, particularly the final one which will get trimmed off again two lines later, so I've ignored the spaces in my code below. I'm also not sure what you're trying to do with the text that was previously selected (if any), so I'm going to assume you want to overwrite it with the new text.

    Bear in mind that this will not work in IE < 9, which does not support selectionStart, selectionEnd nor setSelectionRange().

    Demo: http://jsfiddle.net/timdown/wPfVn/

    Code:

    var val = elmt.value;
    var start = elmt.selectionStart, end = elmt.selectionEnd;
    elmt.value = val.slice(0, start) + txtToIns + val.slice(end);
    elmt.focus();
    var caretPos = start + txtToIns.length;
    elmt.setSelectionRange(caretPos, caretPos);