4

I have a div with style overflow: scroll and it is overflowing on the X-axis. I would like to get the value of how far left/right the user has scrolled within this element, but I can't really figure it out.

I saw that you can quite easily bind the window scroll, but as it is just an element that is scrolling and not the window this won't work. https://svelte.dev/tutorial/svelte-window-bindings

so I tried binding the element, but couldn't really get any meaningful data out of it.

<script>
  let content;
</script>

<div class="carousel">
  <div class="content" bind:this={content}>
    ...
  </div>
</div>
{#if content}
{content.scrollLeft}
{/if}

is it at all possible and am I just missing something?

2 Answers 2

11

You have to find the scroll left of the container/carousel. Not for content. below code will work. check this repl

<script>
  let carousel, sleft;
</script>

<div class="carousel" bind:this={carousel} 
on:scroll={()=>sleft=carousel.scrollLeft}>
  <div class="content" >
    ...
  </div>
</div>

{#if carousel}
{sleft}
{/if}
Sign up to request clarification or add additional context in comments.

2 Comments

Or use the event's target: <div class="carousel" on:scroll){(e)=>sleft=e.target.scrollLeft}>...</div> if you rather not bind the element.
I would suggest updating this to @razvan-tanase 's answer
6

In case anyone wants to bind the vertical AND the horizontal scrolling pixels of an element:

  • element.scrollLeft: horizontal pixels from left
  • element.scrollTop: vertical pixels from top

Here's a REPL with a working example

<script>
  let box
  let xScroll = 0
  let yScroll = 0

  function parseScroll() {
    xScroll=box.scrollLeft
    yScroll=box.scrollTop
  }
</script>

<div class="box" bind:this={box} on:scroll={parseScroll}>
  ...
  (scrollable content)
  ...
</div>

<div class='report'>
  <div>horizontal: {xScroll}</div>
  <div>vertical: {yScroll}</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.