Svelte: wrong button triggered click event

My current setup involves a svelte app in which:

  1. Clicking a button labeled "Show" triggers the display of an input text box and a save button by setting a show variable to true.
  2. Upon clicking the "Save" button, a function is called that changes the show variable back to false.

After running some tests, I noticed that clicking "Show" also seems to activate the on:click event of "Save." I checked Google and found suggestions to add stopPropagation to resolve this issue, but that didn't work for me. Can anyone provide any insight into what mistake I might be making?

If you want to take a look at the code, you can find it here:

Answer №1

I decided to clone the repl and made some modifications to it

Here is the updated code snippet:

<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 encounter a propogation issue because the event listeners are not nested elements

The Save button on:click was originally configured as

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

This setup is inaccurate as on:click={addName()} immediately calls the addName function. If you prefer this syntax, it should be written like this

on:click={addName}

Alternatively, you can use the anonymous function for on:click, which is what I utilized:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on installing React packages during runtime

My React project has a number of packages that need to be installed, but they take up a lot of disk space. I would like to install them only when necessary, after the user interacts with a specific component that requires these packages. Is there a way t ...

What's the best way to manage endless routing options in express.js?

After reviewing the topic of handling routes in Express.js on Stack Overflow, I came across the following example : var express = require("express"); var app = express(); app.get("/", function(request, response) { response.send(&quo ...

Using jQuery to control mouseenter and mouseleave events to block child elements and magnify images

My objective is to create a hover effect for images within specific div elements. The images should enlarge when the user hovers their mouse over the respective div element. I plan to achieve this by adding a child element inside each div element. When the ...

Leverage the values of object properties from a pair of JavaScript arrays containing objects

I am working with two arrays let arr1 = [{'id': 'ee', 'seat': '12'}, {'id': 'aa', 'seat': '8'} ] let arr2 = [ {'id': 's22', 'num': '&ap ...

What is the best way to prevent handleSubmit from triggering a re-render when moved to a different

Just started experimenting with React and ran into an issue that I can't seem to find a solution for anywhere. I have a basic search form that interacts with an API. If an invalid value is returned, it displays an H3 element with an error message lik ...

Text alignment issue in Material UI Data Grid Component

Currently, I am working with a DataGrid component nested inside a div that is enclosed within a Box component. I am facing issues in centering the content of the DataGrid and styling the header text. The code snippet I'm using is: Blockquote <B ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...

Attempting to iterate through the div in order to collect all of the checkboxes and assign a label to each one

I am attempting to modify a piece of JavaScript code in order to locate all checkboxes, assign names to them, and then add label attributes with CSS for accessibility purposes. Here is the snippet of my existing code: <tr class="el-table__row" ...

Working with DOT in URLs using AngularJS UI-Router

I am currently facing an issue while trying to authenticate users using the Google API. The problem arises when the return data in the parameters contain a DOT within the token, causing the server to break as it requests a page that does not exist. However ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

Generating HTML using a filter

I have been working on creating a filter that will render HTML tags. Here is the code for my filter: filters: { limitStrLength: function (value, maxLength) { if (value && value.length > maxLength) { let partialVal = value.substr(0, ...

Is it possible for me to include the id attribute in an HTML element that has been generated using React

While working with Selenium to create end-to-end tests for a React-based web application, I noticed that very few HTML elements have the id property set. Since our development team is preoccupied with other tasks, I've taken it upon myself to address ...

Monitoring data updates within an Angular directive

Is there a way to activate a $watch variable in an Angular directive when modifying the data within it (eg. adding or removing data), without assigning a completely new object to that variable? Currently, I am loading a basic dataset from a JSON file usin ...

Extracting data from hidden columns in jQuery DataTables

I am facing an issue with a table where 2 columns are hidden by the dataTables api. When I delete a row, I need to send the data from these columns via ajax to remove it from the database. In the past, I had no problem deleting rows that didn't conta ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

"Exploring the Power of ZF2 with Restful APIs and Image

I am currently in the process of developing a website utilizing Zend Framework 2 in combination with AngularJS. The backend consists of a restful webservice running on ZF2, while AngularJS is used on the client side to interact with this webservice. My ne ...

Unable to identify the element ID for the jQuery append operation

After attempting to dynamically append a textarea to a div using jQuery, I encountered an issue. Despite the code appearing to work fine, there seems to be a problem when trying to retrieve the width of the textarea using its id, as it returns null. This s ...

Ways to change a value in an array within MongoDb

My array value is being overridden by $set, how can I update it properly? var obj = // contains some other data to update as well obj.images=images; // updating obj with images [] Units.update({_id: 'id', {$set: obj}); Ultimately, my MongoDB ...

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...