Javascript: Move caret to last character

The following function will work in all major browsers, for both textareas and text inputs:

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

However, you really shouldn’t do this whenever the user clicks on the textarea, since the user will not be able to move the caret with the mouse. Instead, do it when the textarea receives focus. There is also a problem in Chrome, which can be worked around as follows:

Full example: http://www.jsfiddle.net/ghAB9/3/

HTML:

<textarea id="test">Something</textarea>

Script:

var textarea = document.getElementById("test");
textarea.onfocus = function() {
    moveCaretToEnd(textarea);

    // Work around Chrome's little problem
    window.setTimeout(function() {
        moveCaretToEnd(textarea);
    }, 1);
};

Leave a Comment