Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  67] [ 3]  / answers: 1 / hits: 49290  / 10 Years ago, wed, february 19, 2014, 12:00:00

I'm trying to set the cursor in a text field with a focus function. I've made some research but none of the provided solutions seemed to work in Google Chrome. In Internet Explorer and Firefox this solution is working fine:



The js:



$('#Search').focus(function() {
var SearchInput = $('#Search');
var strLength= SearchInput.val().length;
SearchInput.focus();
SearchInput[0].setSelectionRange(strLength, strLength);
});


The HTML:



<input type=text id=Search value=Hello World />


Here's the link to my jsfiddle.



Is there any way to make this work in Google Chrome too?


More From » jquery

 Answers
5

It seems like the focus event is fired before the cursor is placed when you focus an input, a hacky workaround would be to use a setTimeout like so:



$('#Search').focus(function() {
setTimeout((function(el) {
var strLength = el.value.length;
return function() {
if(el.setSelectionRange !== undefined) {
el.setSelectionRange(strLength, strLength);
} else {
$(el).val(el.value);
}
}}(this)), 0);
});


Try this fiddle: http://jsfiddle.net/esnvh/26/



Edited to 0ms timeout, as @SparK pointed out this is enough to push to end of execution queue.


[#72437] Tuesday, February 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;