JQuery.focus () works differently in every browser. How to prevent this?

When I try to do .focus(), I expect to set focus on the input element and see the cursor after the 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, the input gets focus, but the cursor is at the beginning.

What can I do to prevent this and get the right behavior for all browsers?

Example here: http://jsbin.com/ozojol/edit#javascript,html

PS. focus().val('').val(value)the method does not work in IE ... What other workarounds exist?

+5
source share
3 answers

selectionStart selectionEnd TextRange IE < 9. .

: http://jsbin.com/azapuy

:

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);
+7

The only common behavior is select()that it selects the input text in all major browsers (it cannot confirm whether it works in all browsers).

0
source

All Articles