Search code examples
sveltesvelte-3

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.


Solution

  • 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>