Entry
How can I scroll a TEXTAREA?
How can I add text in a TEXTAREA so that it is scrolled into view?
Feb 17th, 2001 03:58
Martin Honnen,
IE4+ provides two different solution for scrolling the TEXTAREA. The
first simply set
textAreaReference.scrollTop
either to
0
to scroll to the top, or to
textAreaReference.scrollHeight
to scroll to the bottom. That way the textarea content is scrolled but
the caret/cursor position in it not. But using the text range object
associated with a TEXTAREA in IE4+ you can also set the caret to the
end or beginning of the text content and that way the textarea also
scrolls.
Here is an example demonstrating both approaches:
<HTML>
<HEAD>
<TITLE>
TextArea scrolling in IE4+
</TITLE>
<SCRIPT>
function scrollToTop (element) {
if (document.all)
element.scrollTop = 0;
}
function scrollToBottom (element) {
if (document.all)
element.scrollTop = element.scrollHeight;
}
function setCaretToStart (input) {
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.select();
}
}
function setCaretToEnd (input) {
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(false);
range.select();
}
}
</SCRIPT>
<SCRIPT>
var i = 3;
</SCRIPT>
</HEAD>
<BODY>
<INPUT TYPE="button" VALUE="addLine and scroll to bottom"
ONCLICK="document.all.aTextArea.value += '\n' + i++ + ':
Kibology';
scrollToBottom(document.all.aTextArea);"
>
<INPUT TYPE="button" VALUE="addLine and set caret to end"
ONCLICK="document.all.aTextArea.value += '\n' + i++ + ':
Kibology';
setCaretToEnd(document.all.aTextArea);"
>
<BR>
<INPUT TYPE="button" VALUE="scroll to top"
ONCLICK="scrollToTop(document.all.aTextArea);"
>
<INPUT TYPE="button" VALUE="scroll to bottom"
ONCLICK="scrollToBottom(document.all.aTextArea);"
>
<BR>
<INPUT TYPE="button" VALUE="set caret to start"
ONCLICK="setCaretToStart(document.all.aTextArea);"
>
<INPUT TYPE="button" VALUE="set caret to end"
ONCLICK="setCaretToEnd(document.all.aTextArea);"
>
<BR>
<TEXTAREA ID="aTextArea" ROWS="3" COLS="20" WRAP="soft">
1: Kibology
2: Kibology</TEXTAREA>
</BODY>
</HTML>