In this article I will explain with an example, how to implement automatically scroll to bottom functionality in HTML TextArea using
JavaScript in HTML.
HTML Markup
The following HTML Markup consists of following elements:
TextBox – For capturing the text.
Button – For adding the TextBox text to the HTML TextArea.
The HTML INPUT Button has been assigned with a
JavaScript click event handler.
TextArea – For capturing the text entered in the INPUT TextBox.
<input id="txtSample"type="text"value="Sample Text" />
<input id="btnAdd" type="submit" value="Add" onclick="AddSampleText()" />
<hr />
<textarea id="textBox" rows="2" cols="20" style="height: 100px"></textarea>
Adding lines to HTML TextArea and Scroll to Bottom using JavaScript
When the INPUT
Submit button is clicked,
AddSampleText JavaScript function gets triggered.
Inside the
AddSampleText JavaScript function, HTML TextArea is referenced.
Then, the text from the INPUT TextBox is captured and set to the HTML TextArea.
Finally, the HTML TextArea scrollTop position is set to its height using scrollHeight property, which enforces the scroll bar of HTML TextArea to scroll to the bottom.
<script type="text/javascript">
function AddSampleText() {
// Referencing TextArea element.
var textarea = document.getElementById('textBox');
// Setting TextBox value in TextArea element.
textarea.value += document.getElementById('txtSample').value + "\n";
// Setting TextArea scroll position.
textarea.scrollTop = textarea.scrollHeight;
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads