Drag and Drop
The drag and drop
interaction provides a way to drag and drop content, such as elements or files, from one location to another.
Example
Drag a product into your basket
๐ฅ
๐
Sources
+page.svelte
<script lang="ts">
import Basket from './Basket.svelte'
import Product from './Product.svelte'
const products = ['๐ง', '๐งด', '๐ชฅ', '๐ฅ', '๐ฅ', 'โ', '๐บ', '๐
', '๐']
</script>
<div class="mb-4 flex w-fit flex-wrap gap-2 rounded">
{#each products as value}
<Product {value} />
{/each}
</div>
<p class="mb-2 text-xs opacity-50">Drag a product into your basket</p>
<Basket items={['๐ฅ', '๐']} />
Basket.svelte
<script lang="ts">
import { useDrop } from 'louisette'
export let items: string[] = []
const { drop, hovering } = useDrop({
onDrop: (event) => {
const item = event.dataTransfer.getData('text/plain')
items = [...items, item]
},
})
</script>
<div
use:drop
class="mb-2 flex min-h-[3rem] w-full flex-wrap gap-2 rounded-md border-2 border-transparent bg-amber-50 p-2 shadow dark:bg-amber-950"
class:is-hovering={$hovering}
>
{#each items as item}
<div class="select-none p-1">{item}</div>
{/each}
</div>
<style lang="postcss">
.is-hovering {
@apply border-dashed border-amber-500 transition-colors;
}
</style>
Product.svelte
<script lang="ts">
import { useDrag } from 'louisette'
export let value: string
const { dragging, drag, draggableAttrs } = useDrag()
</script>
<button
use:drag={value}
{...$draggableAttrs}
class="rounded border-2 border-transparent p-2 transition-colors transition-opacity hover:bg-neutral-200 dark:hover:bg-neutral-700"
class:is-dragging={$dragging}
>
{value}
</button>
<style lang="postcss">
.is-dragging {
@apply border-amber-500 opacity-50;
}
</style>