davidjerleke / embla-carousel

A lightweight carousel library with fluid motion and great swipe precision.
https://www.embla-carousel.com
MIT License
5.8k stars 175 forks source link

`slidesInView` is one select event behind #291

Closed vajkri closed 2 years ago

vajkri commented 2 years ago

Bug is related to

Embla Carousel version

Describe the bug

CodeSandbox

Steps to reproduce

  1. Go to line 52 in 'App.tsx'
  2. Open console
  3. Click on "Next" and/or "Prev" a couple of times
  4. Observe, that slidesInView is one click behind

Expected behavior

Thanks in advance

davidjerleke commented 2 years ago

Hi @vajkri,

Thank you for your question. By default, the slidesInView method returns the slides in view at the current carousel scroll location when the method is called, not the target/destination. This is useful when you want fine grain control. For example, if you want to track slides in view as the carousel is scrolling, you can attach it to the scroll event. But I think you’re looking for the target parameter:

An example:

function logSlidesInView() {
  const slidesInView = embla.slidesInView(true); // <-- Pass true to the slidesInView method
  console.log(slidesInView);
}

embla.on('select', logSlidesInView);
embla.on('pointerUp', logSlidesInView);

Note that I added pointerUp event because if you have a carousel with dragFree enabled, dragging might not change the selected snap at all times, but it could change which slides are in view and not.

Let me know if it helps.

Best, David

vajkri commented 2 years ago

Perfect, thanks your for quick reply. Passing true solved it for me :-)

michaelaltmann commented 11 months ago

@davidjerleke This answer suggests that slidesInView takes a target argument that can be true or false. That does not seem to be in the current API. See https://github.com/davidjerleke/embla-carousel/blob/master/packages/embla-carousel/src/components/EmblaCarousel.ts#L213