How do I set textarea scroll bar to bottom as a default?

I have a textarea that is being dynamically reloaded as user input is being sent in. It refreshes itself every couple seconds. When the amount of text in this textarea exceeds the size of the textarea, a scroll bar appears. However the scroll bar isn't really usable because if you start scrolling down, a couple seconds later the textarea refreshes and brings the scroll bar right back up to the top. I want to set the scroll bar to by default show the bottom most text. Anyone have an idea of how to do so?


Solution 1:

pretty simple, in vanilla javascript:

var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;

Solution 2:

You can use this with jQuery

$(document).ready(function(){
    var $textarea = $('#textarea_id');
    $textarea.scrollTop($textarea[0].scrollHeight);
});

Solution 3:

In your HTML ...

<textarea id="logTextArea" style="width:600px;height:200px;"></textarea>

In your Javascript ...

<script language="javascript">

    function loadLog(logValue) {
        logTa = document.getElementById("logTextArea")
        logTa.value = logValue;
        scrollLogToBottom()
    }

    function scrollLogToBottom() {
        logTa = document.getElementById("logTextArea")
        logTa.scrollTop = logTa.scrollHeight;
    }

    loadLog("This is my really long text block from a file ... ")

</script>

I have found that you need to put the code to set the scrollHeight into a separate function after loading the new value into the text area.