I have a page with a very long textarea used for editing large amounts of texts. Normally, as you type, when the caret approaches the bottom of the textarea, the page will automatically scroll to keep the caret always within the viewport (Firefox will scroll by a single line at a time, Chrome will scroll the caret into the center of the viewport).
My problem comes from the fact that I am programmatically changing the contents of the text area based on what the user types. In some cases this involves adding extra content, thus pushing the caret out of view.
As soon as the user hits a key, the autoscroll kicks in and the caret is scrolled into view -- but not before, so as the user is typing they lose sight of the caret. I had hoped I could simply trigger key events on the textarea for the browser to autoscroll, but triggered events don't fully emulate user behavior and I do not get a response.
The only solution I can see now is to try to get the XY coordinates of the caret by:
Is there a simpler way to do this?
To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.
If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value.
I hate to suggest adding a whole library for one problem, but consider looking at CodeMirror. It handles all such stuff for you, and is fairly simple to use.
http://codemirror.net/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With