Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Close other dropdown on click in svelte

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading