Coder Perfect

Do you want to get to the bottom of the div?

Problem

I’m making a chat using Ajax requests, and I’m having trouble getting the messages div to scroll to the bottom.

Everything is wrapped in this div:

#scroll {
    height:400px;
    overflow:scroll;
}

Is there a way to have it default to scrolling to the bottom using JS?

Is there a method to keep the page scrolling down after an ajax request?

Asked by kush

Solution #1

On my website, I utilize the following:

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

Answered by Paige Ruten

Solution #2

If you’re using jQuery scrollTop, this is a lot easier:

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

Answered by andsien

Solution #3

You can try the following code:

function scrollToBottom (id) {
   var div = document.getElementById(id);
   div.scrollTop = div.scrollHeight - div.clientHeight;
}

To make a smooth scroll with JQuery, follow these steps:

function scrollSmoothToBottom (id) {
   var div = document.getElementById(id);
   $('#' + id).animate({
      scrollTop: div.scrollHeight - div.clientHeight
   }, 500);
}

On JSFiddle, you may see an example.

This is why it works:

clientHeight, scrollTop, scrollHeight

Answered by Tho

Solution #4

using jQuery animate:

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

Answered by DadViegas

Solution #5

A newer technique that is compatible with all modern browsers is:

this.scrollIntoView(false);

Answered by tnt-rox

Post is based on https://stackoverflow.com/questions/270612/scroll-to-bottom-of-div