Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .focus() works differently in each browser. How to prevent that?

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?

like image 335
ValeriiVasin Avatar asked Jul 02 '12 15:07

ValeriiVasin


2 Answers

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);
like image 85
Tim Down Avatar answered Oct 18 '22 15:10

Tim Down


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

Live Demo

like image 29
Farahmand Avatar answered Oct 18 '22 16:10

Farahmand