0

linking these two stack overflow posts:

Chat box, auto scroll to bottom Automatically scroll down chat div

I have tried a solution from both:

const chatWindow = document.getElementById('chat-content');
chatWindow.scrollTop = chatWindow.scrollHeight;

and

const chatWindow = document.getElementById('chat-content');
const xH = chatWindow.scrollHeight;
chatWindow.scrollTo(0, xH);

and now the code within the context of the code:

this.twilioconversationservice.receiveworkingconversation()
      .subscribe(
        (req : any)=>{
          if(req != null){
            this.thisconversation = req;
            this.thisconversation.on('messageAdded', ()=>{
              this.thisconversation.getMessages().then((res: any)=>{
                this.messages = res.items;
                const chatWindow = document.getElementById('chat-content');
                chatWindow.scrollTop = chatWindow.scrollHeight;
              });
            });
          }
        });

see from this picture the scroll bar has not fully reached the bottom

But as you can see from the picture included in this post, the scroll bar has not finished its scroll. To where the last message that was sent is not in view.

Is this a code issue? Or am I scrolling at the wrong time?

  • Is this not some mistiming issue? Im thinking that the new message hasnt finished rendering yet when you get `chatWindow.scrollHeight`. – xGeo Sep 03 '21 at 06:19
  • But how would we solve that. A set timeout maybe say for 400 ms or something. But what happens when the chat is really going and we are getting a ton of messages? Wouldn't that cause conflict? – Christopher Jakob Sep 03 '21 at 07:04

1 Answers1

0

so its kinda of a hack at least I think so but whatevs. I just added a setTimeout of 500ms

check it

this.twilioconversationservice.receiveworkingconversation()
      .subscribe(
        (req : any)=>{
          if(req != null){
            this.thisconversation = req;
            this.thisconversation.on('messageAdded', ()=>{
              this.thisconversation.getMessages().then((res: any)=>{
                this.messages = res.items;
                setTimeout(()=>{
                  const chatWindow = document.getElementById('chat-content');
                  chatWindow.scrollTop = chatWindow.scrollHeight;
                },500);

              });
            });
          }
        });

woot

  • How are you rendering the messages? You might be able to trigger the scroll on render rather than waiting for the setTimeout. Also, when you receive the messageAdded event the details of the message should be in the event object. So you should be able to append the new message to your existing list of messages, rather than using `getMessages` to load all the messages again. – philnash Sep 06 '21 at 23:46