简体   繁体   中英

Meteor.js Chat - scrollToBottom(); only works from sending tab

I was following this tutorial chat-tutorial/chat-tutorial-part-4 by rdickert, especially for the scrollToBottom function.

The purpose of this function is to scroll to bottom whenever a new message gets sent inside the chat. But right it only scrolls the tab from which the person sent it. Messages sent by other people (tabs) don't seem to trigger this function for the rest of the present users inside this chat room.

I tested it out with two tabs open, once in Chrome, second time I used the first tab in Chrome and another tab in Firefox. Same result both ways.

This is where I store the scrollToBottom-Function:

imports/api/chat/chat.js

var autoScrollingIsActive = false;
 scrollToBottom = function scrollToBottom (duration) {
  var messageWindow = $(".chatWindow");
  var scrollHeight = messageWindow.prop("scrollHeight");
  messageWindow.stop().animate({scrollTop: scrollHeight}, duration || 0);
};

Then, I want to use the function on the ui-part

imports/ui/components/chat/chat.js

This is the event where the message is getting actually sent by the user.

'keypress #text'(event) {
  if (event.keyCode == 13) {
    event.preventDefault();
    const text = document.getElementById('text').value;
    Meteor.call('chat.start', text, (error) => {
      if (error){
        alert(error.error);
      } 
      else {
        scrollToBottom(200);//Function triggers after msg is sent
      }
    });
  }
}

I also tried to trigger the scrollToBottom-Function with the onRendered-template, but it was the same outcome

 Template.message.onRendered(function () { 
  scrollToBottom(250);
 });

Could anyone explain to me whats the reason behind this behavior? Thanks!

The onRendered callback is triggered on each new message so it should work.

The problem might come from the scrolling function. Try to replace

messageWindow.stop().animate({scrollTop: scrollHeight}, duration || 0);

with

$('html').stop().animate({scrollTop: scrollHeight}, duration || 0);

Sorry, I found my error. I iterated the messages inside the message-template. Not inside the chatWindow-Template like instructed.

{{#each messages}}
{{> message}}
{{/each}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM