user2014429
user2014429

Reputation: 2577

move caret to end of textarea on focus

I thought this would be quite a simple thing to do but I can't get it to work. I am using the following code but with no success. I know this does not work in ie, I am using chrome. here is a jsFiddle to demonstrate. Thanks

$('#ta').focus(function(){
  this.selectionStart = this.value.length;
});

Upvotes: 0

Views: 1611

Answers (3)

Howard Renollet
Howard Renollet

Reputation: 4739

This is a cross-browser and jQuery compliant solution (it supports multiple elements in a given selector).

Tested in Chrome 40x, IE 11, and FireFox 34x

$("textarea").focus(function () {
    for (var i = 0; i < $(this).length; i++) {
        var el = $(this)[i]
        window.setTimeout(function () {
            if (el !== null) {
                if (el.createTextRange) {
                    var range = el.createTextRange();
                    range.move('character', el.value.length);
                    range.select();
                }
                else {
                    if (el.selectionStart || el.selectionStart === 0) {
                        el.focus();
                        el.setSelectionRange(el.value.length, el.value.length);
                    }
                    else {
                        el.focus();
                    }
                }
            }
        }, 1)
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="ta">focus on me</textarea><br />
<textarea id="ta2">focus on me</textarea>

Upvotes: 2

Joe Sager
Joe Sager

Reputation: 787

Just in case you wanted to see how to fix you original solution so that it may work, here is what you had to do:

$('#ta').focus(function (e) {
    var element = this;
    setTimeout(function () {
        element.selectionStart = element.value.length;
    }, 1);
});

The position must be set after a very short delay (1 millisecond is sufficient in my case) because it seems as though the cursors position is set to where you click after the focus function is finished, so you are setting the cursor to be at the end of the input but then it is immediately being placed where the user clicked right after this happens

Fiddle: http://jsfiddle.net/zb5uoL3t/

Upvotes: 1

krzysiej
krzysiej

Reputation: 898

a quick one

$('#ta').focus(function(){
    moveCursorToEnd(document.getElementById('ta'));
});

function moveCursorToEnd(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();
    }
}

http://jsfiddle.net/9xaxz53x/1/

Upvotes: -1

Related Questions