sveltejs / svelte-scroller

A <Scroller> component for Svelte apps
https://svelte.dev/repl/76846b7ae27b3a21becb64ffd6e9d4a6
Other
347 stars 25 forks source link

Execute functions based on scroll index #11

Open jbixon13 opened 4 years ago

jbixon13 commented 4 years ago

Is it possible to execute arbitrary functions such as:

<script>
    let index 

    function count() {
        console.log('this executes upon scrolling to the third section');
    }

    if (index = 2) {
        count()
    }
</script>

This is possible in something like scrollama.js, and I would like to use svelte-scroller to do so if possible as it's already built into Svelte.

jtrim-ons commented 3 years ago

I think it should work if you do this:

$: if (index == 2) {
    count();
}

I've opened PR #14 to avoid repeated calls to the function (you could alternatively use another variable to keep track of whether index has changed from its previous value).

maxgraze-zz commented 3 years ago

Hello! I was wondering this too. I tried this as well but my function ended up getting called over 100 times and glitching.

jtrim-ons commented 3 years ago

@maxgraze here is the version where I tried to fix the issue of repeated function calls: https://github.com/jtrim-ons/svelte-scroller/blob/fewer-section-updates/Scroller.svelte . If you decide to give it a try, let us know if it works.