skip to Main Content

I have an application with a page that has a chat feature. I want this to look and feel like most chat apps, the newest messages are at the bottom of the page, and you scroll up to see more previous messages.

I’ve got the pagination aspect of the infinite scroll working fine. When you scroll to the top of the current page, you get the next set of previous messages.

Unfortunately, when you get to the top of the page, the next page loads in, but the scroll position stays at the top of the page, essentially "skipping" you to the top of the next page of messages. It’s a bad UX.

Atm, I’m adding "markers" for each page. Just divs with ids for the page number. When the next set of messages loads in, I scroll to the latest page marker, keeping the UX better.

This just feels hacky, and I feel like I’m missing something more simple to keep the scroll from behaving this way. Any thoughts would be appreciated!

2

Answers


  1. I would try to save the position before loading the new messages and then scroll to that. Something like:

    const chatContainer = document.getElementById('chat-container');
    
    const prevScrollHeight = chatContainer.scrollHeight;
    
    //here you load and append new messages
    
    chatContainer.scrollTop = chatContainer.scrollHeight - prevScrollHeight;
    

    You have to keep saving messages in batches tho, so maybe not with different divs (with page number as id like you’re doing) but with an array of objects with ids and content (so that you know what to load when scrolling reaches top).

    Login or Signup to reply.
  2. CSS Overflow Scroll.

    setInterval(() => {
      // Your code to be executed
      let text = document.createTextNode("Hello World");
      let div = document.createElement("div");
      div.appendChild(text);
      document.querySelector("article").append(div);
    }, 1000); // 1000 milliseconds = 1 second
    article {
      height: 100px;
      width: 300px;
      outline: 1px solid black;
      overflow:scroll;
    }
    <article>
    
    </article>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search