Guilherme Vaz Guilherme Vaz - 7 months ago 66
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[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!


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 {
    }}(this)), 0);

Try this fiddle:

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