How to scroll the bottom of a div as data is being added to Meteor?

I am writing a messaging application in Meteor, and I want to configure it so that when a user enters a message, it scrolls down to the bottom of the div for both of them. I save the message in a list messagesin the conversation document in the collection Conversations. I use cursor.observeChanges, and it seems that the callback is triggered before the data is displayed on the client side so that it does not scroll to the end.

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 corresponding css:

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

And here is js:

Tracker.autorun(function(){
    ...
    Conversations.find(conversationId).observeChanges({
      changed: function(id, fields){
         $("#chat-messages").scrollTop($("#chat-messages").prop("scrollHeight"));
      }
    });
});
+4
source share
2 answers

, , Blaze - , Javascript , Tracker.afterFlush. , , :

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

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

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

+7

:

Template, ( ) . , .

, - JS :

chatBox.js

Template.chatBox.helpers({
    chatMessages: function() {
       return Conversations.find({conversationId: conversationId},
      {sort: {d: -1}, limit: 20}).fetch().reverse();
    },
});

(chatMessages.d conversationId , , chat-messages div, 20 )

, :

Template.chatBox.helpers({
    chatMessages: function() {
       //scroll down not animated
       $('#chat-messages').scrollTop($('#chat-messages').prop('scrollHeight'));
       return Conversations.find({conversationId: conversationId},
      {sort: {d: -1}, limit: 20}).fetch().reverse();
    }
});

:

Template.chatBox.helpers({
    chatMessages: function() {
       //scroll down with animation
       $('#chat-messages').animate({scrollTop: $('#chat-messages').prop('scrollHeight')}, 500);
       return Conversations.find({conversationId: conversationId},
      {sort: {d: -1}, limit: 20}).fetch().reverse();
    }
});

" " .

, .

0

Source: https://habr.com/ru/post/1598071/


All Articles