I am creating a chat using Ajax requests and I\'m trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
If you don't want to rely on scrollHeight
, the following code helps:
$('#scroll').scrollTop(1000000);
Java Script:
document.getElementById('messages').scrollIntoView(false);
Scrolls to the last line of the content present.
You can use the HTML DOM scrollIntoView Method like this:
var element = document.getElementById("scroll");
element.scrollIntoView();
On my Angular 6 application I just did this:
postMessage() {
// post functions here
let history = document.getElementById('history')
let interval
interval = setInterval(function() {
history.scrollTop = history.scrollHeight
clearInterval(interval)
}, 1)
}
The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.
This will let you scroll all the way down regards the document height
$('html, body').animate({scrollTop:$(document).height()}, 1000);
You can use the following code:
function scrollToBottom (id) {
var div = document.getElementById(id);
div.scrollTop = div.scrollHeight - div.clientHeight;
}
To perform a smooth scroll with JQuery:
function scrollSmoothToBottom (id) {
var div = document.getElementById(id);
$('#' + id).animate({
scrollTop: div.scrollHeight - div.clientHeight
}, 500);
}
See the example on JSFiddle
Here's why this works:
Ref: scrollTop, scrollHeight, clientHeight