Does anybody know how to move the keyboard caret in a textbox to a particular position?
For example, if a text-box (e.g. input element, not text-area) has 50 characters in it and I want to position the caret before character 20, how would I go about it?
This is in differentiation from this question: jQuery Set Cursor Position in Text Area , which requires jQuery.
Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon @kd7's code here's what I've come up with.
Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera
Cross-browser caret positioning technique (example: moving the cursor to the END)
The meat and potatoes is basically @kd7's setCaretPosition, with the biggest tweak being
if (el.selectionStart || el.selectionStart === 0)
, in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.In chrome the biggest issue was that just giving it
.focus()
wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itselfel.value = el.value;
before calling our function, and now it has a grasp & position with the input to use selectionStart.The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):
http://snipplr.com/view/5144/getset-cursor-in-html-textarea/
In case the code gets lost again, here are the two main functions:
I would fix the conditions like below:
If you need to focus some textbox and your only problem is that the entire text gets highlighted whereas you want the caret to be at the end, then in that specific case, you can use this trick of setting the textbox value to itself after focus:
Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript
A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:
The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.
Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).
An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus: