Tinder-like swipeable cards component for svelte.
card-swiper-svelte.mp4
- Built with tailwind
- Reuses cards (only two cards, that are swapped)
- Customizable (easily customize the card ui and data)
- Modern: uses @use-gesture/vanilla for gesture handling
- Uses TypeScript
-
You need to have tailwind installed in your project, see here for installation instructions.
-
Download the
CardSwiper
folder fromsrc/libs
to your projectssrc/lib
folder. -
Install dependency
@use-gesture/vanilla
npm i @use-gesture/vanilla
<script lang="ts">
import { CardSwiper } from '$lib/CardSwiper';
// function that returns the data for each card, by default has title, description and image
let data = (index) => {
return {
title: 'Card ' + index,
description: 'Description ' + index,
image: '/profiles/' + index + '.webp'
};
};
</script>
<div class="h-screen w-screen">
<CardSwiper cardData={data} />
</div>
Customize the Card.svelte
file to your needs, if you need to pass in more data to your card, edit the CardData
type in CardSwiper/index.ts
(and add the prop to Card.svelte
).
You can control the cards programmatically by calling the swipe function.
<script lang="ts">
import { CardSwiper } from '$lib/CardSwiper';
let swipe: (direction?: 'left' | 'right') => void;
</script>
<div class="h-screen w-screen">
<CardSwiper bind:swipe />
<button on:click={() => swipe('left')}>Swipe left</button>
<button on:click={() => swipe('right')}>Swipe right</button>
</div>
<script lang="ts">
import { CardSwiper } from '$lib/CardSwiper';
function onSwipe(cardInfo: {
direction: Direction;
element: HTMLElement;
data: CardData;
index: number;
}) {
console.log('swiped', cardInfo.direction, 'on card', cardInfo.data.title);
}
</script>
<div class="h-screen w-screen">
<CardSwiper {onSwipe} />
</div>
Show a threshold overlay when swiping like so (set to 0 if no threshold reached, 1 if right threshold, -1 if left threshold is reached):
<script>
import { CardSwiper } from '$lib/CardSwiper';
let thresholdPassed = 0;
</script>
<CardSwiper bind:thresholdPassed />
{#if thresholdPassed !== 0}
<div class="absolute w-full h-full inset-0 flex items-center justify-center text-9xl">
{thresholdPassed > 0 ? '👍' : '👎'}
</div>
{/if}
You can also set the minimum threshold as a percentage of the card width (default is 0.5) and the minimum speed (default is 0.5).
<CardSwiper minSwipeDistance={0.3} minSwipeVelocity={0.3} />
Per default Cards can be swiped with Arrow keys, too. You can disable this by setting arrowKeys
to false
.
if you want the user to just be able to move the card left or right in a curve, set the anchor to a high number (at least 1000, recommended >5000).
MIT