JS Fiddle Demo
HTML
From Jonathan Levine's comment, I realized that this answer works for me.
Fiddle Demo
JavaScript
$('#scroll-to-cursor').on('click', function() {
$('textarea').focus();
$.event.trigger({ type : 'keypress' }); // works cross-browser
// new KeyboardEvent('keypress'); // doesn't work in IE and Safari
/* var evt = document.createEvent('KeyboardEvent');
evt.initKeyEvent('keypress', true, true, null, false, false, false, false, 0, 32);
$textarea.dispatchEvent(evt);
evt = document.createEvent('KeyboardEvent');
evt.initKeyEvent('keypress', true, true, null, false, false, false, false, 8, 0);
$textarea.dispatchEvent(evt); */
});
/*
To test:
1) Click somewhere in the textarea to place cursor
2) Scroll away so cursor isn't visible
3) Click "Scroll to Cursor" button
*/
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 the KeyboardEvent() constructor, which is compliant and works in all browsers except IE (Safari is a question mark).
Edit 2: Using $.event.trigger({ type : 'keypress' });
instead of new KeyboardEvent()
works just as well, and works in all browsers.