HTML
<textarea rows='5'>
sdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadj
</textarea>
<br />
<button id='scroll-to-cursor'>Scroll to Cursor</button>
JavaScript
$('#scroll-to-cursor').on('click', function() {
// ?
});
Desired Outcome
- Click somewhere in the textarea to place cursor.
- Scroll away so cursor isn't visible.
- Click "Scroll to Cursor" button.
- Textarea scrolls to the position of the cursor
Note: I'm using jQuery.
The only way I could figure out how to scroll is to use jQuery's scrollTop
function. It sets the scroll position to "the number of pixels that are hidden from view above the scrollable area".
I've diagrammed the problem below. Passing in the length of that red line (in pixels) to scrollTop
should do the trick. But I can't figure out how to get the length of the line.
This is my spin on things.
I found that Audi Nugraha’s solution worked when testing, but not when I tried it in an Electron application.
A solution which did work for me was to position the cursor to the beginning and then blur/focus.
I have incorporated the above into a function:
Does the job.
Example: https://jsfiddle.net/syy25x69/
To select a text in IE see: Set textarea selection in Internet Explorer
From Jonathan Levine's comment, I realized that this answer works for me.
Fiddle Demo
JavaScript
Explanation
When the user presses a key, the browser does two things:
This solution just simulates that (without actually entering any text).
Edit: The old solution isn't standards compliant.
initKeyEvent
is deprecated. The update only uses theKeyboardEvent()
constructor, which is compliant and works in all browsers except IE (Safari is a question mark).Edit 2: Using
$.event.trigger({ type : 'keypress' });
instead ofnew KeyboardEvent()
works just as well, and works in all browsers.