scrolling to div bottom not working after loading ajax data

Viewed 129

so I have a div with a scrollbar. When you start off the div start off at the bottom. However when I load the new ajax data after my post request, it is no longer scrolling to the bottom. I believe it's going to the "previous" bottom before the ajax data is added can you guys help.

<div id='messages'>
  <div id='message_box'>
    text messages
  </div>
</div>
// this works page start off with div scroll to the bottom
$(document).ready(function() {
  var objDiv = document.getElementById("messages");
  objDiv.scrollTop = objDiv.scrollHeight;
})

// ajax post request works, but the scroll to bottom in the success method isn't working
// it is scrolloing to the second last message not last how do i fix this?
var url_link = window.location.href;
$.ajax({
  data: {
    'text': 'text'
  },
  type: "POST",
  url: url_link,
  success: function() {

    $('#message_box').load(url_link + ' #message_box');
    var objDiv = document.getElementById("messages");
    objDiv.scrollTop = objDiv.scrollHeight;
  },
  error: function(e) {
    console.log("Bad request: " + e);
  }
#messages {
  overflow-y: scroll;
  width: 100px;
  height: 250px;
}

to recap. the issue is that the message div is not scrolling to the bottom of the div after the ajax post method. The height is going to the second last message not the last message so I need to scroll down to see the new message. How do I fix this thanks

1 Answers

From the structure of the HTML it appears that the load() call is placing content in to #message_box which affects the height of #messages. Therefore you need to update the scrollTop in the callback of load(), not of the $.ajax() call. Try this:

let scrollToBottom = $container => $container.prop('scrollTop', $container.prop('scrollHeight'));

jQuery($ => {
  let $messages = $('#messages');
  scrollToBottom($messages); // scroll down on page load
  
  let url_link = window.location.href;
  $.ajax({
    data: { text: 'text' },
    type: "POST",
    url: url_link,
    success: function() {
      $('#message_box').load(url_link + ' #message_box', () => scrollToBottom($messages));
    },
    error: function(e) {
      console.log("Bad request: " + e);
    }
  });
})

Note that I made some minor amendments to the logic to avoid repetition and ensure the code runs after the DOM has loaded.

Related