Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea auto-scroll to the bottom

Tags:

javascript

I have a textarea that I append data to with textarea.value += "more text\n"; and I would like it to "stay" scrolled to the bottom, so it would always show the last line.

I have read that I should do:

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

But I tried that (http://jsfiddle.net/BenjiWiebe/mya0u1zo/) and I can't get it to work.

What am I doing wrong?

like image 209
BenjiWiebe Avatar asked Oct 24 '14 23:10

BenjiWiebe


1 Answers

You need to set scrollTop each time you append text:

var textarea = document.getElementById('textarea_id');
setInterval(function(){
    textarea.value += Math.random()+'\n';
    textarea.scrollTop = textarea.scrollHeight;
}, 1000);

http://jsfiddle.net/mya0u1zo/2/

like image 109
celeritas Avatar answered Oct 11 '22 13:10

celeritas