Ulvi
Ulvi

Reputation: 1021

Preventing double click on onclick in Svelte

I use onclick to fire my function but I want to prevent the function to be called when double click action is made.

How can I achieve it on Svelte? Does Svelte have any special way of registering only one click but not double?

Any help is very much appreciated.

Upvotes: 1

Views: 2444

Answers (3)

efb
efb

Reputation: 19

there is now an event modifier "once" that achieves this. https://svelte.dev/tutorial/event-modifiers

<script>
    function handleClick() {
        console.log('click');
    }
</script>

<button on:click|once={handleClick}>Click me</button>

Upvotes: 1

Tholle
Tholle

Reputation: 112787

You could implement this behavior by e.g. setting a boolean to true when the click handler is called, and use a timeout to reset it back to false after some period of time. If this boolean is true on a new click you ignore it.

Example (REPL)

<script>
    let hasBeenClicked = false;
    
    function handleClick() {
        if (hasBeenClicked) return;
        
        hasBeenClicked = true;
        setTimeout(() => {
            hasBeenClicked = false;
        }, 200);
        
        console.log('click');
    }
</script>

<button on:click={handleClick}>Click me</button>

Upvotes: 3

Stephane Vanraes
Stephane Vanraes

Reputation: 16411

There is nothing build in into Svelte to do this.

But this can be easily done by wrapping the function you want to execute in a throttle function, which will basically limit the number of clicks one can make within a specific time frame.

There are a lot of snippets for throttle functions to be found online, or you can use one of the myriad npm packages that do it for you.

Upvotes: 1

Related Questions