user3516183 user3516183 - 5 months ago 55
Ajax Question

Auto Scroll to bottom of div after ajax request

None of the answers in here work before people start marking as duplicate!

The poll function is a php file, simply gets the content of a text file, I want the browser to scroll to the bottom of the div content once the request (fires every 3 seconds) has completed. Here is some code

<div id="content_div_id">

</div>

<script>
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh,3000);
$.post('pollchat.php', function(data) {
$('#content_div_id').html(data);
});

}




My problem is after the 3 second refresh it is at the top of the chat content again. . . .

The entire thing is nested inside a window like so:

<div class="portlet-body chat-widget" style="overflow-y: auto; width: auto; height: 300px;">
<div class="row">
<div class="col-lg-12">
<p class="text-center text-muted small">January 1, 2014 at 12:23 PM</p>
</div>
</div>

<div id="content_div_id">

</div>
</div>

Answer

The point is: your div with id="content_div_id" is not scrollable.

I created a simulation snippet, using a different values:

  • Add style="overflow-y: hidden; width: auto; height: auto;" to div with id="content_div_id"
  • I used jQuery.get instead of jQuery.post (you need to use post in your code)
  • I used a different url (you need to use your url)
  • I moved the timer inside the ajax so that it starts again and again (You could use a settimer, but if you do so you need to plan how and when to stop it)
  • I used jQuery append instead of jQuery html because I assume you want to append instead of substitute. It's up to you which one you need.

var i = 0;
function startRefresh() {
  $.get('https://api.github.com/users', function(data) {
    $('#content_div_id').append(i + ': ' + data[0].id + '<br>');
    i += 1;
    var myDiv = $('div.portlet-body.chat-widget');
    myDiv.scrollTop(myDiv[0].scrollHeight - myDiv[0].clientHeight);
    setTimeout(startRefresh, 300);
  });
}
$(function () {
  startRefresh();
});
#content_div_id {
  width: 50%;
  height: 100px;
  overflow-y: scroll;
}
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

<div class="portlet-body chat-widget" style="overflow-y: auto; width: auto; height: 300px;">
    <div class="row">
        <div class="col-lg-12">
            <p class="text-center text-muted small">January 1, 2014 at 12:23 PM</p>
        </div>
    </div>

    <div id="content_div_id" style="overflow-y: hidden; width: auto; height: auto;">

    </div>
</div>

Comments