Search code examples
javascriptjqueryhtmlcsssimplebar

JQuery automatically scroll div to bottom


I have page messages page that automatically gets messages through ajax but the containing div of the message is always scrolled to top like normal. I want it like any other messaging app that automatically scroll to the last message which is at the bottom of the div. The body is not scroll-able because it is linked with height of the client device but other divs inside are scroll-able and the targeting div is the one with id messages. I have a plugin caller

    <div class="chat-messages-body" id="chat-messages-body" style="display:flex; flex-direction: column-reverse;">
      <div data-simplebar="init" id="chat-messages-body-init">
        <div class="chat-messages-list" id="chat-messages-list">

<div id="messages">
<!-- loading chats -->
  <div id="" style="padding-top:10%;"> 
    <center class="text-primary rotate-infinite">
      <img src="/images/loading_chats.png" width="35px;"></img>
    </center>
    <p class="text-center" style="color:#ff003c;">Loading...</p>
  </div> 
<!-- .loading chats -->
</div>

        </div><!-- .chat-messages-list -->
      </div><!-- SimpleBar INIT -->
    </div><!-- .chat-messages-body -->

and my jquery code that that loading messages and scrolling to buttom but it's not working

//jquery get messages, refresh every 5 seconds and scroll to messages bottom
  window.setInterval(function(){
    var id = $("#id").val(); //get transaction id
    $(document).ready(function(){
        $("#messages").load('/jsServerSide/messages.php', {id:id});
    });
    $('#messages').animate({
        scrollTop: $('#messages').get(0).scrollHeight
    }, 2000);
  }, 5000);

Here is my current body fixed height code

//Dont scroll page, use fixed 2000px height
  $(document).ready(function() {
      $('#chat-scroll').animate({
          scrollTop: $('#chat-scroll').get(0).scrollHeight
      }, 2000);
  });
// .Dont scroll page, use fixed 2000px height

I used this plugin to create custom scrollbars SimpleBar


Solution

  • Use the third parameter on the load function which is a callback that is called whenever AJAX is finished. Place the animation function inside that callback to only start scrolling whenever there is new content.

    var $messages = $('#messages');
    window.setInterval(function(){
      var id = $("#id").val(); //get transaction id
      $messages.load('/jsServerSide/messages.php', {id:id}, function() {
        $messages.animate({
          scrollTop: $messages.prop('scrollHeight')
        }, 2000);
      });
    }, 5000);