Scroll to bottom of div?

Scroll to bottom of div?

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 {

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?


Solution 1:

Here’s what I use on my site:

var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;

Solution 2:

This is much easier if you’re using jQuery scrollTop:


Solution 3:

using jQuery animate:

  scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);

Solution 4:

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

And that’s how it works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

Solution 5:

var mydiv = $("#scroll");

Works from jQuery 1.6

Solution 6:

Newer method that works on all current browsers: