ben mi
ben mi

Reputation: 75

How can I smooth scroll an element to the top of its scrollable parent without scrolling the rest of the page?

I have a scrollable container, with many elements. I want to be able to smoothly scroll an element to the top of the scrollable container, but without affecting the rest of the page, so the rest of the page shouldn't be scrolled.

The behaviour should be similar to scrollIntoView({ behavior: 'smooth', inline: 'start', block: 'start' }).

I created an example Svelte REPL to play around with: https://svelte.dev/repl/10ef4392a20e46c588f89d7622479196?version=3.55.1

When clicking the button, line 20 should be smoothly scrolled to the top of the container, without the page scrolling down. So the result should look like this:

enter image description here

The element that I want scrolled to should be at the top of the container, not at the bottom.

I know there are many scroll questions related to javascript, but I wasn't able to find a good answer for this. Is there a way to do this?

Upvotes: 0

Views: 242

Answers (1)

ben mi
ben mi

Reputation: 75

I found the scroll-into-view-if-needed package that can do exactly this, by allowing you to specify a boundary. For anyone else that needs it: https://www.npmjs.com/package/scroll-into-view-if-needed?activeTab=readme

Upvotes: 0

Related Questions