Search code examples
javascriptsveltesvelte-3

svelte: click event triggered on wrong button


I have a svelte app where

  1. licking a button "Show" sets a show variable to true which shows a input text box and a save button.
  2. Clicking the "Save" button calls a function which sets the show variable to false

Testing shows that clicking Show also triggers the on:click of Save. Google tells me to add stopPropagation to fix this issue, but it does not fix this issue. Any hints on what is my mistake?

A repl with my code is available at https://svelte.dev/repl/592a544ac59a45b385ab153dec7a42f1?version=3.55.1


Solution

  • I forked the repl and made some changes to it https://svelte.dev/repl/b897aa42e87d4adc8c04b381b5a66692?version=3.55.1

    Here is the new code:

    <script>
        var name = ''
        let names=[];
        let show=false;
        function addName(){
            console.log("Clicked");
            show=false;
            if (name.length > 0){
                names.push(name);
                console.log(names)
            }
        }
    </script>
    <button on:click={()=>(show=true)} > Show
    </button>
    {#if show}
    <input bind:value={name} type="text">
    <button on:click={()=> {addName()}}>Save</button>
    {/if}
    <h1>Hello {name}!</h1>
    

    You shouldn't have a propogation issue because the event listeners are not nested elements https://www.tutorialrepublic.com/javascript-tutorial/javascript-event-propagation.php

    Your Save button on:click was setup like

    <button on:click={addName()}>Save</button>
    

    This definition is not correct because on:click={addName()} calls the addName function immediately. If you use this syntax you likely need to write it like this

    on:click={addName}
    

    Otherwise you can write it like your other on:click with an anonymous function (which is what I did).

    on:click={()=> {addName()}}