5

When I try to do .focus() I expect to set focus on input element and to see cursor after last character of the value. And I see it in IE.

In safari/chrome input gets focus and all text is selected. In firefox/opera input gets focus, but cursor is in the beginning.

What could I do to prevent that and get correct behavior for all browsers?

An example is here: http://jsbin.com/ozojol/edit#javascript,html

PS. focus().val('').val(value) method doesn't work in IE... What other workarounds exist?

ValeriiVasin
  • 8,628
  • 11
  • 58
  • 78

3 Answers3

7

You can use the input's selectionStart and selectionEnd properties in most browsers and some nasty TextRange stuff in IE < 9. Here's some code adapted from an answer to a similar question.

Demo: http://jsbin.com/azapuy

Code:

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

var input = $('#i')[0];
input.focus();
moveCaretToEnd(input);
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Works in FF 16 - nice! You have to be careful to call moveCaretToEnd with the actual dom element (as shown above), not the jQuery object. The latter does not work. – sieppl Nov 01 '12 at 10:56
1

There is a great lightweight plugin to move the caret to the end of the content within your element. jQuery Caret

Live Demo

Farahmand
  • 2,731
  • 1
  • 24
  • 27
0

The only common behavior is the select(), that selects the input text in all major browsers (can't confirm if it works in all browsers).

Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69