Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cursor position at the end of input text in Google Chrome

Tags:

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?

like image 450
Guilherme Vaz Avatar asked Feb 19 '14 13:02

Guilherme Vaz


People also ask

How to place the cursor at the end of text in JavaScript?

We can place the cursor at the end of the text in a text input element by using different JavaScript functions. HTMLInputElement.setSelectionRange (): The HTMLInputElement.setSelectionRange () is a method that sets the start and end positions of the current text selection in an <input> or <textarea> element.

How to move the cursor to the end of the input?

Call the focus () method on the input element. The focus method will move the cursor to the end of the input element's value. Here is the HTML for the examples in this article. Copied! And here is the related JavaScript code. Copied! We used the setSelectionRange to set the start and end positions of the current text selection in the input element.

How do I navigate the page with a text cursor?

Turn on Navigate pages with a text cursor. Tip: You can also turn on caret browsing with the keyboard shortcut F7 . On Chromebook, the keyboard shortcut is Ctrl + Search + 7, or Ctrl + Launcher + 7. Was this helpful? How can we improve it?

How to set cursor position in content editable elements like div tag?

In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document.createRange () method. First, create Range and set position using above syntax. On button click assign input value to range function to return cursor position on div.


1 Answers

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.

like image 147
ruuska Avatar answered Oct 09 '22 05:10

ruuska