Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1649

Auto-scrolling of parent doesn't work when child elements put into a separate component

$
0
0

I'm trying to add more features to my chat app. And now I try to implement auto-scrolling to the bottom of chat window when new messages appear on that window. And this piece of code works as expected:

<script>// some other codelet isScrolledUpByUser;function onScrollHandler(event) {  const { target } = event;  if (!target) {    return;  }  const { scrollTop, scrollHeight, offsetHeight } = target;  isScrolledUpByUser = scrollTop !== scrollHeight - offsetHeight;}function scrollToBottom(node, _) {  return {    update() {      if (!isScrolledUpByUser) {        node.scroll({ top: node.scrollHeight, behavior: "smooth" });      }    },  };}</script><div  class="wrapper"  use:scrollToBottom={[$messages, $isTyping]}  on:scroll={onScrollHandler}>  {#if $messages.length > 0}    {#each messages as message, index (message.id)}<Message {message} />    {/each}  {:else}<div>sorry, no messages yet</div>  {/if}  {#if $isTyping}<div>user is typing...</div>  {/if}</div><style lang="scss" scoped>  .wrapper {    flex: 1;    max-height: 100%;    overflow-y: auto;  }</style>

But I'd like to put the logic of displaying messages to a separate Messages component because the current component (Chat window) already has pretty much code.

<script>// same javascript code</script><div  class="wrapper"  use:scrollToBottom={[$messages, $isTyping]}  on:scroll={onScrollHandler}><Messages {$messages} />  {#if $isTyping}<div>user is typing...</div>  {/if}</div><style lang="scss" scoped>  /* same styles */</style>

And the messages component:

<script>  import Message from "../messageBubbles/Message.svelte";  export let messages;</script>{#if messages.length > 0}  {#each messages as message, index (message.id)}<Message {message} />  {/each}{:else}<div>sorry, no messages yet</div>{/if}

But now the parent component does not autoscrolls itself when getting new messages. But I noticed that if I get rid of this condition in onScrollHandler function:

      if (!isScrolledUpByUser) {        node.scroll({ top: node.scrollHeight, behavior: "smooth" });      }

autoscroll will work just fine. But then I can't check if user scrolled up.I have no idea how to fix this.


Viewing all articles
Browse latest Browse all 1649

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>