Guilherme Vaz Guilherme Vaz - 6 months ago 45
jQuery Question

How to set cursor position at the end of input text in Google Chrome

This is my first question here so, I'm sorry in advance if I do something wrong.

I'm trying to set the cursor in a text field with a focus function. I've made some research but none of the provided solutions seemed to work in Google Chrome. In Internet Explorer and Firefox this solution is working fine:

The js:

$('#Search').focus(function() {
var SearchInput = $('#Search');
var strLength= SearchInput.val().length;
SearchInput.focus();
SearchInput[0].setSelectionRange(strLength, strLength);
});


The html:

<input type="text" id="Search" value="Hello World" />


Here's the link to my jsfiddle.

Is there any way to make this work in Google Chrome too? Thanks a lot!

Answer

It seems like the focus event is fired before the cursor is placed when you focus an input, a hacky workaround would be to use a setTimeout like so:

$('#Search').focus(function() {
    setTimeout((function(el) {
        var strLength = el.value.length;
        return function() {
            if(el.setSelectionRange !== undefined) {
                el.setSelectionRange(strLength, strLength);
            } else {
                $(el).val(el.value);
            }
    }}(this)), 0);
});

Try this fiddle: http://jsfiddle.net/esnvh/26/

Edited to 0ms timeout, as @SparK pointed out this is enough to push to end of execution queue.