Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I scroll to the last item in an {#each} block in Svelte

In svelte, I’m currently templating out an array of messages like this:

{#each messages as message, i}
    {@const isLast = i === messages.length - 1}
    
    <div class="card" class:active={isLast}>
        {message}
    </div>

{/each}

I then have a function where I can append a new item to the array

function addNextWord(){
    messages = [...messages, words[index]];
}

When I do so, I’d like to scroll the very last item into view (using something like Element.scrollIntoView).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But how can I get a reference to just the last item in the loop?

Demo in Svelte REPL

>Solution :

Just use an action.

const initialCount = messages.length;
const scroll = node => {
    if (messages.length > initialCount)
        node.scrollIntoView()
}
<div class="card" use:scroll ...

REPL

In the vast majority of cases actions are just better than bind:this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading