Xzoky
Xzoky

Reputation: 57

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.

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' });

Upvotes: 4

Views: 6775

Answers (1)

brunnerh
brunnerh

Reputation: 185553

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 use:scrollToBottom={list} ...>

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

REPL

Upvotes: 11

Related Questions