Scroll a textarea to a given position with jQuery

Updated . Posted . Visible to the public.

Browsers make this very hard. Even when you explicitely set the selection inside the textarea (e. g. using jquery-fieldselection Show archive.org snapshot ) the browser will not scroll the textarea to this selection.

What you can do instead is abuse browsers' behavior that they scroll to the end of a textarea when it gets focus. So we set the textarea's value to the text before the position, then focus it, then reset it to its original value:

function scrollTextareaToPosition($textarea, position) {
  var text = $textarea.val();
  var textBeforePosition = text.substr(0, position);
  $textarea.blur();
  $textarea.val(textBeforePosition);
  $textarea.focus();
  $textarea.val(text);
  $textarea.setSelection(position, position); // assumes that you use jquery-fieldselection.js
}

I'm sorry!

Also see Scroll a textarea to a given line with jQuery.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2014-11-06 10:25)