I am creating a chat using ajax requests in rails and I'm trying to get a div to scroll to the bottom without much luck.
I am wrapping everything in this div:
#scroll {
height:400px;
overflow:scroll;
}
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scrolled to the bottom after an ajax request?
This is much easier if you're using jQuery:
Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.
That will make sure that the scroll event is fired after the data has been inserted into the DOM.
You can use the following code:
To perform a smooth scroll, use the following code (require jQuery):
See the sample on JSFiddle
And that's how it works:
Ref: scrollTop, scrollHeight, clientHeight
Found this really helpful, thank you.
For the Angular 1.X folks out there:
Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular.
Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well.
Java Script:
document.getElementById('messages').scrollIntoView(false);
Scrolls to the last line of the content present.
Here's what I use on my site: