Search code examples
javascripthtmldomsveltedom-manipulation

Getting into a scrolling loop when shifting DomElements on scroll


I'm building a virtual grid of sorts, that will place content into the viewport as it's required, particularly on user scrolling.

I've been able to achieve this kind of behavior with React, but I seem to be having trouble with svelte.

    <script>
    let scroll;
    $: height = Math.floor(scroll/200)*200;
</script>

<svelte:window bind:scrollY={scroll} />


<div class="holder" style="height:{height}px"></div>
<div class="box"></div>



<style>
    :global(body) {
        height: 20000px;
    }
    .box {
        width: 200px;
        height: 200px;
        background-color: aqua;
    }
    .holder {

    }
</style>

REPL

As I scroll, and the bottom div is increased in height to raise the blue box, something triggers a further scroll, which then triggers a further height increase which triggers a further scroll.

So basically as you scroll a little the scroll bar goes crazy and slides down on pc.

Ideally the page should scroll normally from user inpu.

Not sure if this is a problem with svelte, or if this is some default browser behavior.

Edit: change code and repl to reflect my requirement a bit more, which shows why setting "position: fixed" css wouldn't work.


Solution

  • In your code setting the height of the .holder changes the scroll. So it falls in continuous loop till meets bottom.

    <script>
        let scroll;
        $: top = Math.floor(scroll/200)*200;
    </script>
    
    <svelte:window bind:scrollY={scroll} />
    
    <div class="box" style="top:{top}px"></div>
    
    <style>
        :global(body) {
            height: 20000px;
        }
        .box {
            position: absolute;
            top: 0;
            width: 200px;
            height: 200px;
            background-color: aqua;
        }
    </style>