Alex Rivera | Logout

How do I keep a textarea's caret always within the viewport?

Asked 2012-10-24T21:38:54.237
17

I have a page with a very long textarea used for editing large amounts of texts. Normally, as you type, when the caret approaches the bottom of the textarea, the page will automatically scroll to keep the caret always within the viewport (Firefox will scroll by a single line at a time, Chrome will scroll the caret into the center of the viewport).

My problem comes from the fact that I am programmatically changing the contents of the text area based on what the user types. In some cases this involves adding extra content, thus pushing the caret out of view.

As soon as the user hits a key, the autoscroll kicks in and the caret is scrolled into view -- but not before, so as the user is typing they lose sight of the caret. I had hoped I could simply trigger key events on the textarea for the browser to autoscroll, but triggered events don't fully emulate user behavior and I do not get a response.

The only solution I can see now is to try to get the XY coordinates of the caret by:

  1. Finding the character position of the caret.
  2. Building a div that mirrors the content of the textarea with a marker at the caret position.
  3. Measuring the position of the marker.

Is there a simpler way to do this?

Edit
Report

1 Answer

0

Since you already are on the javascript path and suppose a dynamic textarea height would pose a design issue, you could try autoresizing your textarea by content:

function resizeTextarea(textarea) {
  var lines = textarea.value.split('\n');
  var width = textarea.cols;
  var height = 1;
  for (var i = 0; i < lines.length; i++) {
    var linelength = lines[i].length;
    if (linelength >= width) {
      height += Math.ceil(linelength / width);
    }
  }
  height += lines.length;
  textarea.rows = height;
}

I know this does not answer the specifics outlined in your post but it provides an alternative approach fitting your question title. So even if it's not useful for you, it may be just that for others visiting this question.

I personally hate too small text areas and dependin on the case, would prefer them autosizing.

answered 2013-02-06T09:25:53.523

Your Answer