In this section we will create dropdown on hoverable in svelte with tailwind css.
Install Tailwind CSS in Svelte with Typescript Using Vite
Tool Use
Tailwind CSS 3.x
Svelte
Examples
svelte with tailwind css simple dropdown on hover.
<script>
let isOpen = false;
</script>
<div class="relative">
<button
class="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600"
on:mouseover={() => (isOpen = true)}
on:mouseout={() => (isOpen = false)}
>
Dropdown On Hover
</button>
{#if isOpen}
<div class="absolute w-48 py-2 mt-2 bg-white rounded shadow-lg">
<div
class="block px-4 py-2 text-gray-800 hover:bg-indigo-500 hover:text-white"
>
Item 1
</div>
<div
class="block px-4 py-2 text-gray-800 hover:bg-indigo-500 hover:text-white"
>
Item 2
</div>
<div
class="block px-4 py-2 text-gray-800 hover:bg-indigo-500 hover:text-white"
>
Item 3
</div>
</div>
{/if}
</div>
svelte with tailwind css on hover dropdown menu list.
<script>
let dropdownItems = [
{ label: 'Option 1', value: 'option1' },
{ label: 'Option 2', value: 'option2' },
{ label: 'Option 3', value: 'option3' }
];
let selectedItem = dropdownItems[0].value;
let isOpen = false;
function selectItem(item) {
selectedItem = item.value;
isOpen = false;
}
</script>
<div class="relative">
<button
class="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600"
on:mouseover={() => (isOpen = true)}
on:mouseleave={() => (isOpen = false)}
>
{#each dropdownItems as item}
{#if item.value === selectedItem}
{item.label}
{/if}
{/each}
</button>
{#if isOpen}
<div class="absolute w-48 py-2 mt-2 bg-white rounded shadow-lg">
{#each dropdownItems as item}
<div
class="px-4 py-2 cursor-pointer hover:bg-gray-200"
on:click={() => selectItem(item)}
>
{item.label}
</div>
{/each}
</div>
{/if}
</div>