This is the simple dropdown component I use. repl here
<script>
let show = false;
</script>
<div>
<button on:click={() => show = !show }>Show Dropdown</button>
{#if show}
<div>
<a href="/">Option 1</a>
<a href="/">Option 2</a>
<a href="/">Option 3</a>
<a href="/">Option 4</a>
</div>
{/if}
</div>
<style>
a { display: block; }
</style>
I am using this component in parent three times as follow:
<script>
import Dropdown from './dropdown.svelte';
</script>
<div>
<Dropdown />
<Dropdown />
<Dropdown />
</div>
Once I click first dropdown its respective dropdown content opens, but upon clicking next dropdown how do I close previous dropdowns and open only the one that is clicked?
Thank You
>Solution :
Well i never touched svelte but i know an method how to do it.
You can use focus and blur events
You add tabindex="0" to the element and whenever you open it, you focus the element. Now, whenever you click outside of the element the blur event will be triggered. It even gets triggerd if you click outside of your browser.
<script>
import { tick } from 'svelte';
let show = false;
let dropdownElement;
async function showDropdown() {
show = !show;
//we need to wait with tick, until DOM nodes have mounted
await tick();
dropdownElement.focus()
}
</script>
<div>
<button on:click={ showDropdown }>Show Dropdown</button>
{#if show}
<div on:blur={() => show = false} tabindex="0" bind:this={dropdownElement}>
<div>Option1</div>
<div>Option2</div>
<div>Option3</div>
</div>
{/if}
</div>
I use div instead of a tags because when you click on the a tags, the parent loses its focus.