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

Scroll to bottom of element in sveltekit

How do I make an element scroll to the bottom when the page is loaded?

I’ve tried doing it in onMount, but the element is undefined.

I’m accessing the element using bind:this.

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

When I try to make the element scroll later (when clicking a button, for example) it works.

Here’s the code I’m using to make the element scroll to the bottom (taken from svelte repl):

node.scroll({ top: node.scrollHeight, behavior: 'smooth' });

>Solution :

This works just fine:

onMount(() => scrollToBottom(element))

REPL

If the element is guaranteed to be on the page (i.e. not inside something that would only add the element conditionally like an #if), it will be bound in onMount.

The code of the REPL is maybe not equivalent to your actual code?


For many DOM interactions actions are a better fit. In this case scrollToBottom would already be a suitable action for the initial scroll. It can be expanded to also trigger when the list changes like this:

const scrollToBottom = node => {
    const scroll = () => node.scroll({
        top: node.scrollHeight,
        behavior: 'smooth',
    });
    scroll();

    return { update: scroll }
};
<div style="height:250px;overflow:auto;"
     use:scrollToBottom={list}>

(list is passed as argument to make it a dependency on when update is triggered)

REPL

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