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?
I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .
It uses
Mutation Observers
(https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) which makes it usable only on modern browsers (though polyfills exist)So basically the code does just that :
I made a fiddle to demonstrate the concept : https://jsfiddle.net/j17r4bnk/
Using jQuery, scrollTop is used to set the vertical position of scollbar for any given element. there is also a nice jquery scrollTo plugin used to scroll with animation and different options (demos)
if you want to use jQuery's animate method to add animation while scrolling down, check the following snippet:
small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):
Works from jQuery 1.6
https://api.jquery.com/scrollTop/
http://api.jquery.com/prop/
You can also, using jQuery, attach an animation to
html,body
of the document via:$("html,body").animate({scrollTop:$("#div-id")[0].offsetTop}, 1000);
which will result in a smooth scroll to the top of the div with id "div-id".
Javascript or jquery:
Css: