7

Possible Duplicate:
Set cursor at a length of 14 onfocus of a textbox

I am able to do that in firefox and IE. But for some reason its not working in Chrome and Safari :(

I am simply using below line onfocus

$('input:text').focus(
function(){
      document.getElementById('id').setSelectionRange(0, 0);
    });

Can someone please tell me how to do similar thing in Chrome and safari?

Community
  • 1
  • 1
Deepak Yadav
  • 1,724
  • 3
  • 23
  • 38
  • I already tried it before posting this question. There are other similar questions too, but both createTextRange and setSelectionRange are not working for me on my safari n chrome.. any suggestions why? – Deepak Yadav Nov 18 '11 at 23:36
  • This should not be closed as duplicate as there are no answers to the question referenced above that solve this issue - that it fails in Webkit. – gilly3 Nov 19 '11 at 00:28

2 Answers2

15

The problem is that Chrome (I haven't heard of Safari doing this as well, but I'll take you word for it) kills the selection after the focus event has fired, so you need to add a timer. The following is adapted from my answer here:

How to place cursor at end of text in textarea when tabbed into

However, this generally isn't good usability: it's contrary to what the user expects and removes useful functionality when using the mouse (i.e. the caret going to the location the user clicks). You can probably get around that with some handling of mousedown and mouseup events.

Live demo: http://jsfiddle.net/timdown/z9DhX/1/

Code:

function moveCaretToStart(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = 0;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(true);
        range.select();
    }
}

var textBox = document.getElementById("id");

textBox.onfocus = function() {
    moveCaretToStart(textBox);

    // Work around Chrome's little problem
    window.setTimeout(function() {
        moveCaretToStart(textBox);
    }, 1);
};
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
5

Webkit is resetting the caret position as part of the focus event. You need to defer execution of your script until after the event has fully fired. Using setTimeout with a delay of 0 is good enough:

$(":text").focus(function () {
    var input = this;
    setTimeout(function() {
        input.setSelectionRange(0, 0);
    }, 0);
});

Working demo: http://jsfiddle.net/ZkqGH/1/

gilly3
  • 87,962
  • 25
  • 144
  • 176
  • thanks for answering, but its not working yet :( .. my cursor goes at the end of textbox's value when I click inside it(only in chrome and safari). In firefox is working fine as expected. – Deepak Yadav Nov 18 '11 at 22:07
  • 1
    @Deepak - I've rewritten my answer. `setSelectionRange()` works fine, you just need to delay execution to prevent Chrome from resetting the caret position. – gilly3 Nov 19 '11 at 00:22