0

My question is similar to this question. But I want the scroll to go to bottom EVEN IF user scrolls up. The answers to the tagged question are working provided that scroll to bottom stops if user scrolls up.

I've written the below code which works UNLESS user scrolls up and it stays there even if content is added beneath.

setTimeout(() => {
    let d = document;
    d.querySelector(".chat-scroll").scrollTo(0, d.body.scrollHeight);
}, 100);
Aman Devrath
  • 398
  • 1
  • 3
  • 21

1 Answers1

0

You can try like this:

.chat-container .chat-message:last-child
{
  scroll-snap-align: end;
}

Additionally, you can run a MutationObserver on the scroll container and when there is new content - your event handler will scroll to the bottom of the container.

If you're using Vue.js - then you can take advantage of the following directive:

  // Monitors an element and scrolls to the bottom if a new child is added (always:false = prevent scrolling if user manually scrolled up)
  // <ul class="messages" v-chat-scroll="{always: false}">
  //   <li class="message" v-for="n in messages">{{ n }}</li>
  // </ul>
  Vue.directive('chat-scroll',
  {
    bind: function(el, binding)
    {
      var timeout, scrolled = false;

      el.addEventListener('scroll', function(e)
      {
        if (timeout) window.clearTimeout(timeout);
        timeout = window.setTimeout(function()
        {
          scrolled = el.scrollTop + el.clientHeight + 1 < el.scrollHeight;
        }, 200);
      });

      (new MutationObserver(function(e)
      {
        var config = binding.value || {};
        var pause = config.always === false && scrolled;
        if (pause || e[e.length - 1].addedNodes.length != 1) return;
        scrollToBottom(el);
      })).observe(el, {childList: true});
    },
    inserted: scrollToBottom
  });
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26