Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I scroll to the bottom of a div as data is added in Meteor?

I'm writing a messenger application in Meteor, and I want to set it up such that when either user types a message it scrolls down to the bottom of the div for both of them. I am storing the message in a list called messages in a conversation document in the collection Conversations. I am using cursor.observeChanges, and it seems that the callback fires before the data is rendered on the client side so it doesn't scroll all the way to the bottom.

Here is the html:

<template name="chat">  
    {{> chatBox}}
</template>

<template name="chatBox">
    <div class="chat-box">
        <div id="chat-messages">
            {{#each chatMessages}}
                <div class="individual-message">
                    {{message}}
                </div>
            {{/each}}
        </div>
        <form id="chat-input">
            <input class="add-message" autocomplete="off" placeholder="Write something..." name="text" type="text">
      </form>
    </div>
</template>

Here's the relevant css:

#chat-messages {
    overflow-y: scroll;
    width: 250px;
    height: 450px;
    padding: 15px;
    position: absolute;
}

And here's the js:

Tracker.autorun(function(){
    ...
    Conversations.find(conversationId).observeChanges({
      changed: function(id, fields){
         $("#chat-messages").scrollTop($("#chat-messages").prop("scrollHeight"));
      }
    });
});
like image 761
David Kleiman Avatar asked Jan 07 '23 23:01

David Kleiman


1 Answers

Whenever I run into an issue where Blaze hasn't had a chance to render something in time for a Javascript function to be evoked on it, I use Tracker.afterFlush. This waits until the render cycle is done before running some code, e.g.:

// Inside a Meteor event callback
Tracker.afterFlush(function () {
  var $someItem = $('....');

  $(window).scrollTop($someItem.offset().top);
});

http://docs.meteor.com/#/full/tracker_afterflush

like image 96
CaptSaltyJack Avatar answered Jan 30 '23 23:01

CaptSaltyJack