Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  200] [ 3]  / answers: 1 / hits: 21164  / 13 Years ago, fri, november 18, 2011, 12:00:00

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?


More From » onfocus

 Answers
14

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

[#89025] Thursday, November 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chelseyn

Total Points: 36
Total Questions: 85
Total Answers: 89

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;