I'm trying to get my textarea to scroll to the bottom if new text is inserted. But I just can't get it to work.
HTML
<textarea id="txt-area" readonly rows="21" cols="48"></textarea>
<button class="buttons" value="1">1</button>
<button class="buttons" value="2">2</button>
<button class="buttons" value="3">3</button>
<button class="buttons" value="4">4</button>
<input type="button" class="buttons" value="Test">
<input type="button" class="Backspace" value="DEL">
JavaScript
var values = [];
$(document).ready(function () {
$(".buttons").click(function () {
var cntrl = $(this).html();
if ($(this)[0].nodeName == "INPUT" )
{
cntrl = $(this).attr( "value" );
}
$("#txt-area").val(function (_, val){
return val + cntrl
});
values.push($(this).val());
$("#txt-area").val(values.join("\n"));
});
$('.Backspace').on('click', function () {
values.pop();
$('#txt-area').val(values.join("\n"));
});
});
$(document).ready(function(){
$(".buttons").click(function(){
$('#txt-area').scrollTop($('#txt-area').scrollHeight);
});
});
My code is also in this jsFiddle
I'm trying to get my textarea to scroll to the bottom if new text is inserted. But I just can't get it to work.
HTML
<textarea id="txt-area" readonly rows="21" cols="48"></textarea>
<button class="buttons" value="1">1</button>
<button class="buttons" value="2">2</button>
<button class="buttons" value="3">3</button>
<button class="buttons" value="4">4</button>
<input type="button" class="buttons" value="Test">
<input type="button" class="Backspace" value="DEL">
JavaScript
var values = [];
$(document).ready(function () {
$(".buttons").click(function () {
var cntrl = $(this).html();
if ($(this)[0].nodeName == "INPUT" )
{
cntrl = $(this).attr( "value" );
}
$("#txt-area").val(function (_, val){
return val + cntrl
});
values.push($(this).val());
$("#txt-area").val(values.join("\n"));
});
$('.Backspace').on('click', function () {
values.pop();
$('#txt-area').val(values.join("\n"));
});
});
$(document).ready(function(){
$(".buttons").click(function(){
$('#txt-area').scrollTop($('#txt-area').scrollHeight);
});
});
My code is also in this jsFiddle
Share Improve this question asked May 19, 2016 at 8:05 FanserviceFanservice 251 silver badge5 bronze badges 3- Possible duplicate of [stackoverflow./questions/7381817/… – ozil Commented May 19, 2016 at 8:17
- Possible duplicate of How to have a textarea to keep scrolled to the bottom when updated – LoganMzz Commented Jun 26, 2017 at 14:34
- Possible duplicate of How do I set textarea scroll bar to bottom as a default? – Herohtar Commented Oct 9, 2018 at 13:44
2 Answers
Reset to default 4You need to change
$('#txt-area').scrollTop($('#txt-area').scrollHeight);
to
$('#txt-area').scrollTop($('#txt-area')[0].scrollHeight);
See http://jsfiddle/cPYCV/48/
Add this to your JavaScript
window.setInterval(function() {
var elem = document.getElementById('txt-area');
elem.scrollTop = elem.scrollHeight;
}, 1000);