Read more

Scroll a textarea to a given position with jQuery

Henning Koch
November 06, 2014Software engineer at makandra GmbH

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.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2014-11-06 11:25)