diff --git a/components/content-card-carousel.tsx b/components/content-card-carousel.tsx index ae28aee..fb00ed9 100644 --- a/components/content-card-carousel.tsx +++ b/components/content-card-carousel.tsx @@ -16,6 +16,7 @@ interface ContentCardCarouselProps { cards: ContentCardItem[] } +// correctly works function getVisibleCardCount() { if (typeof window === 'undefined') return 1 if (window.matchMedia('(min-width: 1024px)').matches) return 3 @@ -52,21 +53,26 @@ export default function ContentCardCarousel({ cards }: ContentCardCarouselProps) const maxIndex = useMemo(() => Math.max(cards.length - visibleCards, 0), [cards.length, visibleCards]) + // custom mod function because JS does not have working modulus + function mod(n: number, m: number) { + return ((n % m) + m) % m; + } + useEffect(() => { setCurrentIndex((previous) => Math.min(previous, maxIndex)) }, [maxIndex]) // % of track width — matches flex slide sizes (100% / 50% / 33.333% per breakpoint) - const trackOffsetPercent = cards.length > 0 ? (currentIndex * 100) / cards.length : 0 + const trackOffsetPercent = cards.length > 0 ? ((currentIndex) * -100) / visibleCards : 0 const next = () => { if (maxIndex === 0) return - setCurrentIndex((previous) => (previous >= maxIndex ? 0 : previous + 1)) + setCurrentIndex(mod(Math.abs((currentIndex + 1)), (cards.length))) } const previous = () => { if (maxIndex === 0) return - setCurrentIndex((index) => (index <= 0 ? maxIndex : index - 1)) + setCurrentIndex(mod((currentIndex - 1), (cards.length))) } return ( @@ -76,7 +82,7 @@ export default function ContentCardCarousel({ cards }: ContentCardCarouselProps)