Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross browser "jump to"/"scroll" textarea

I have a textarea with many lines of input, and a JavaScript event fires that necessitates I scroll the textarea to line 345.

scrollTop sort of does what I want, except as far as I can tell it's pixel level, and I want something that operates on a line level. What also complicates things is that, afaik once again, it's not possible to make textareas not line-wrap.

like image 242
Edward Z. Yang Avatar asked Sep 30 '08 22:09

Edward Z. Yang


2 Answers

You can stop wrapping with the wrap attribute. It is not part of HTML 4, but most browsers support it.
You can compute the height of a line by dividing the height of the area by its number of rows.

<script type="text/javascript" language="JavaScript">
function Jump(line)
{
  var ta = document.getElementById("TextArea");
  var lineHeight = ta.clientHeight / ta.rows;
  var jump = (line - 1) * lineHeight;
  ta.scrollTop = jump;
}
</script>

<textarea name="TextArea" id="TextArea" 
  rows="40" cols="80" title="Paste text here"
  wrap="off"></textarea>
<input type="button" onclick="Jump(98)" title="Go!" value="Jump"/>

Tested OK in FF3 and IE6.

like image 123
PhiLho Avatar answered Nov 20 '22 04:11

PhiLho


If you use .scrollHeight instead of .clientHeight, it will work properly for textareas that are shown with a limited height and a scrollbar:

<script type="text/javascript" language="JavaScript">
function Jump(line)
{
  var ta = document.getElementById("TextArea");
  var lineHeight = ta.scrollHeight / ta.rows;
  var jump = (line - 1) * lineHeight;
  ta.scrollTop = jump;
}
</script>

<textarea name="TextArea" id="TextArea" 
  rows="40" cols="80" title="Paste text here"
  wrap="off"></textarea>
<input type="button" onclick="Jump(98)" title="Go!" value="Jump"/>
like image 2
tetkin Avatar answered Nov 20 '22 06:11

tetkin