Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Scrolling a Textarea

I have a textarea html element on my page that gets reloaded via ajax. The whole textarea is returned each time not just its content, and the content grows over time. Along with the textarea i return the following piece of javascript:

<script type="text/javascript" >

var textArea = document.getElementById('outputTextResultsArea');
textArea.scrollTop = textArea.scrollHeight;
</script>

In firefox 3.0.7 this places the scroll bar at the bottom of the textArea, allowing me to see the latest of the output. However in IE 7 i see different behaviour. The scrollbar moves down with the content as intended, but once the content is greater then the textarea height the scroll bar no longer moves down. It seems as if IE is remembering the original scroll height of the element, not the new height.

I am using the xhtml transitional doctype if that helps. Also if this can be achieved with jQuery that would be fine as I have access to that.

Thanks in advance

Neil

like image 519
Neil Foley Avatar asked Mar 13 '09 12:03

Neil Foley


2 Answers

As a quick hack you can just do this:

textArea.scrollTop = 99999;

Another option is to try it in a timer:

setTimeout(function()
{
    var textArea = document.getElementById('outputTextResultsArea');
    textArea.scrollTop = textArea.scrollHeight;
}, 10);
like image 88
Greg Avatar answered Oct 27 '22 18:10

Greg


Using jQuery, $("textarea").scrollHeight(99999) works great on Firefox and Chrome but not on IE. It appears to set it to the max number of lines in the textarea, whereas scrollHeight is supposed to be the number of pixels. (Awesome show great job IE). This appears to work though:

      $("textarea").scrollTop(99999)
      $("textarea").scrollTop($("textarea").scrollTop()*12)

I think this assumes a 12px font-height. I would love to find a more robust/straightforward way to do this.

like image 33
Saul F Avatar answered Oct 27 '22 19:10

Saul F