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' });
>Solution :
This works just fine:
onMount(() => scrollToBottom(element))
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)