flickity icon indicating copy to clipboard operation
flickity copied to clipboard

Move slider on page scroll

Open coreyworrell opened this issue 3 years ago • 2 comments

Test case: https://codepen.io/coreyworrell/pen/dyZPJYB

I am trying to adjust the slider position based on page scroll, but would like to have a smooth transition after scroll has stopped. Right now the movement is just a bit too stiff. Any ideas on how to improve the "fluidity" of it? Something similar to the feel of this: https://lmgonzalves.github.io/scroll-based-animation/

I've seen references to applyForce() and startAnimation() methods but couldn't get them to work well, mostly because I'm not well versed in the Flickity internals.

coreyworrell avatar Jan 27 '22 01:01 coreyworrell

Here's my solution https://codepen.io/desandro/pen/zYPvMyZ

// external js: flickity.pkgd.js
const flick = new Flickity('.carousel', {
    setGallerySize: false,
    prevNextButtons: false,
    pageDots: false,
    draggable: false,
    freeScroll: true,
    wrapAround: true,
})


let lastScroll = 0
window.addEventListener('scroll', onScroll, false)

function onScroll() {
    flick.isFreeScrolling = true;
    flick.startAnimation();
    let diff = window.scrollY - lastScroll
    lastScroll = window.scrollY


    flick.velocity += diff * -0.1;
    flick.x += flick.velocity;
    flick.velocity *= 1 - 0.03;

    let previousX = flick.x
    flick.positionSlider();
}

I'm re-working the logic in animate() and applyForce(). Try adjusting the -0.1 and - 0.03 values to see how that affects the animation

desandro avatar Jan 30 '22 13:01 desandro

@desandro Thanks very much, that works really well. I couldn't quite get it working with the IntersectionObverver/requestAnimationFrame optimization, but just wrapped it in a throttled onScroll and that will work nicely in this instance. Appreciate your help!

Edit: small note if others use in future, use let lastScroll = window.scrollY to avoid a large jump/animation on page load/refresh.

coreyworrell avatar Jan 31 '22 19:01 coreyworrell