jQuery Custom Content Scroller doesn't scroll to bottom

linopolus picture linopolus · May 22, 2013 · Viewed 16.2k times · Source

I use mCustomScrollbar for an element on a page, which gets reloaded at times. It's a messages view, and when the user clicks on another conversation, the messages of this conversation get loaded. However, when I want to scroll to bottom after loading this, as the newest messages are at bottom, it scrolls not to bottom but a few pixels above bottom ("a few" can be randomly between 10 and 200px).

Below is a simplified example:

// code to load another conversation
$(".conversations .conversation").click(function (e) {
    var $this = $(this);
    $.ajax({
        url: W.sprintf('/messages/%s/fetch', $this.attr("data-cid")),
        dataType: 'html'
    }).done(function(data) {
        $('.main_pane.messages').html(data);
        // a function call to set the hight of .main_list.messages goes here
        $(".main_list.messages").mCustomScrollbar(W.scroll_prefs);
        $(".main_list.messages").mCustomScrollbar("scrollTo", "bottom");
        // also tried adding an element at bottom and scrolling to this
        // and scrollTo Number.MAX_VALUE
        // also tried putting the two mCustomScrollbar lines both into
        // setTimeout()
    });
});
<!-- this is what gets loaded -->
#conversation
  .head
    -# some foo
  .conv_body
    .main_list.messages.custom-scroll.hide-scrollbar.start-bottom
      -# basically a bunch of these below
      .listelem.msg
        .left
          = image_tag(user.avatar.image(:icon), size: avatar_size(:icon))
        .right
          %span.datetime= fmt_time(msg[:datetime], :time)
        .middle
          .name= link_to(user.login, user)
          .text= msg[:text]
    #new_message_container.main_input.open.threeline
      = form_for(@message) do |f|
        -# ...

CSS: just a few margins and paddings and colors and stuff, nothing fancy

Answer

Lau picture Lau · Jan 8, 2014

I had the same problem , solved it by first calling the update and then adding a timeout of 1000 before I call the scrollTo bottom

$('#commentArea .mCSB_container ').append('<span class="oneComment">'+outputText+'</span><span class="commentBreaker"></span>');
$("#commentArea").mCustomScrollbar("update");
    setTimeout(function(){
        $("#commentArea").mCustomScrollbar("scrollTo","bottom");
    },1000);