How to Pass Parameters to on:click in Svelte?
Last Updated :
21 Aug, 2024
Parameters are the data that you want to pass to a function when an event, such as a click, occurs. In Svelte, you can pass parameters to the on:click event handler in a couple of ways, either directly within the event handler or by using element references.
In this article, we will explore two different approaches to pass parameters to on:click in Svelte.
Steps to Create a Svelte Application
Step 1: Install Node.js
Make sure Node.js is installed on your machine. You can Install node.js from official website.
Step 2: Create Svelte Application
Open your terminal and run the following command to set up a new Svelte project:
npx degit sveltejs/template svelte-app
Step 3: Navigate to Your Project Directory
Change to the newly created project directory:
cd svelte-app
Step 4: Install Dependencies
Install the required npm packages:
npm install
Project Structure:
The updated dependencies in package.json file are:
"devDependencies": {
"@rollup/plugin-commonjs": "^24.0.0",
"@rollup/plugin-node-resolve": "^15.0.0",
"@rollup/plugin-terser": "^0.4.0",
"rollup": "^3.15.0",
"rollup-plugin-css-only": "^4.3.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-svelte": "^7.1.2",
"svelte": "^3.55.0"
},
"dependencies": {
"sirv-cli": "^2.0.0"
}
Passing Parameters Directly in the Event Handler
In this approach, we are directly passing the parameter 'GeeksforGeeks' to the handleClick function within the on:click event handler. When the button is clicked, the function is invoked with the specified argument, triggering an alert that displays the message with the provided name.
Example: The below example passes parameters directly to the event handler.
HTML
<!--App.svelte-->
<script>
function handleClick(name) {
alert(`Hello, ${name}!`);
}
</script>
<h1 style="color: green; text-align: center;">
GeeksforGeeks
</h1>
<h3 style="text-align: center;">
Approach 1: Passing Parameters
Directly in the Event Handler
</h3>
<div style="text-align: center; margin-top: 20px;">
<button on:click={() => handleClick('GeeksforGeeks')}>
Click me
</button>
</div>
Steps to Run the Application
Open the terminal, run this command from your root directory to start the application
npm run dev
Open your browser and navigate to http://localhost:5000
Output:
Using bind to Pass a Reference
In this approach, we are using bind:this to create a reference to the button element and passing that reference along with other parameters to the handleClick function. When the button is clicked, the event object and the additional parameter 'GeeksforGeeks' are passed to the function, which then updates a message displayed on the page.
Example: The below example uses bind to Pass a Reference.
HTML
<!--App.svelte-->
<script>
let buttonElement;
let message = "Click the button to see the magic!";
function handleClick(event, name) {
message = `Hello, ${name}! You clicked the button with text: "${event.target.textContent}"`;
}
</script>
<h1 style="color: green; text-align: center;">
GeeksforGeeks
</h1>
<h3 style="text-align: center;">
Approach 2: Using bind:this to Pass a Reference
</h3>
<div style="text-align: center; margin-top: 20px;">
<button
bind:this={buttonElement}
on:click={(event) => handleClick(event, 'GeeksforGeeks')} >
Click me
</button>
</div>
<p style="text-align: center; margin-top: 20px;">
{message}
</p>
Output:
Conclusion
You can pass parameters ro on:click in Svelte event handlers using inline arrow functions for simplicity or leverage bind:this to pass element references. Both methods are effective, offering flexibility based on your use case and requirements.
Similar Reads
How to Get Query String Parameter in SvelteKit?
In this article, we will explore how to retrieve query string parameters in SvelteKit applications. Query parameters are often used to pass data in URLs, such as user preferences or search queries. Understanding how to access these parameters is crucial for building dynamic web applications.These ar
3 min read
How to Simulate a Click in JavaScript?
Simulating a click in JavaScript means triggering a click event on an HTML element using code, rather than requiring manual user interaction. This technique is useful for automating actions like clicking buttons, links, or other interactive elements, enhancing web functionality, and triggering hidde
3 min read
How to Access URL Query String in Svelte?
URL query strings are a way to pass parameters to a web page through the URL. They appear after the question mark (?) in a URL and are typically used to convey data or state between different parts of a web application.In Svelte, you can access and manipulate these query parameters to dynamically di
3 min read
How to Import SVG Icons into a Svelte App?
SVG Icons are used in Svelte applications for creating scalable, high-quality graphics that can be easily styled and animated. They are lightweight, making them ideal for enhancing the visual appeal of modern web applications. In this article, we'll explore two different approaches to importing and
3 min read
How To Route Programmatically In SvelteKit?
Routing is an important part of any web application, allowing users to navigate between different views or pages. SvelteKit, a modern framework for building web apps using Svelte, offers powerful routing capabilities both declaratively (through URL-based routes) and programmatically (using JavaScrip
4 min read
How to Persist Svelte Store?
To persist a Svelte store, you can synchronize its state with browser storage like 'localStorage' or 'sessionStorage'. On component mount, retrieve the stored value and initialize the Svelte store with it. Set up a subscription to the store that updates the browser storage whenever the store's state
3 min read
How To Change The Default Port 5000 in Svelte?
In Svelte, the application is by default rendered on port 5000 when using the development server. However, you might want to change this port to avoid conflicts with other applications or to fit specific requirements. It can be done through different approaches, such as updating the package.json fil
3 min read
How to Loop Each Block X Amount of Times in Svelte?
Svelte is a modern JavaScript framework that offers a unique approach to building web applications by compiling components at build time. One common requirement in web development is iterating over a block of code a specific number of times. In Svelte, this can be achieved using the {#each} block. T
3 min read
How to get the Length of the Path in SVG ?
The Scalable Vector Graphics (SVG) is a widely used the XML-based format for describing two-dimensional vector graphics. When working with the SVG paths in JavaScript we may need to determine the length of path for the various purposes such as the animation, drawing or interactive effects. These are
3 min read
How to set a click event once a page or view is loaded in vue.js?
In this article, we will discuss how to set a click event once a page or view is loaded in vue.js. Just like every other JavaScript framework Vue also supports the Mounting hooks. Mounting hooks are often the most used hooks. They allow us to access or modify the DOM of your component just before or
2 min read