Knowing the jQuery Caret plugin, I'm still seeing no way to do the following on a single line text box in HTML (i.e. the input:type=text
control) with JavaScript:
- Programmatically inserting text into a text box
- Setting the caret to the end.
- Making the caret visible (i.e. scroll the text box content)
I know how to do 1. and 2., just for 3. I have found no way of doing it.
To illustrate it:
My question is:
Is there any way to reliable put the caret at the end of the text and scroll it into the view?
(I can think of simulating pressing the END
key or something like that, but I'm unsure whether this would be the best option).
So with the help of Mark and Rob W, I finally managed to solve it.
My additional challenge was that the text box already has the focus, which came out is an issue (I'm using the whole stuff in the
OnClientItemSelected
of the Ajax Toolkit'sAutoCompleteExtender
).So my solution is:
It's working for me successfully in Google Chrome, Firefox and Internet Explorer 9. Hopefully it works in other browsers, too.
I'm marking Mark's comment as the answer.
It's not possible to implement this behavior cross-browser. FireFox supports the
KeyboardEvent.initKeyPress
method, which allows key events to be simulated.See the comments at the function below for an explanation. I've successfully tested this function in FireFox 3.6.22, 7.0.1 and Chrome 14.
The function itself is plugin-independent. Fiddle: http://jsfiddle.net/Jskbb/1/
If you want to put the caret at the end and scroll to the bottom of a textarea, this works perfectly :
It will place the caret at the end, and then smoothly scroll the window to the bottom.
//hack to get cursor at end:
edit: should note focus first:
try to set the scrollLeft property of the input, as:
You can use scrollWidth to get a better guess on the final value, but using a high one can ensure correctness on most cases.
You could try triggering a right key press after focus.