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 Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)