Scroll to bottom of div? – Dev

The best answers to the question “Scroll to bottom of div?” in the category Dev.

QUESTION:

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:

#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?

ANSWER:

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

$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);

ANSWER:

Here’s what I use on my site:

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

ANSWER:

using jQuery animate:

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

ANSWER:

You can try the code below:

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:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight