In the previous tutorial, we learned how to loop through data and dynamically generate HTML elements using Svelte's {#each}
block. Today, we'll take our skills a step further and learn how to handle events, specifically how to pass data to event handlers and perform actions like deleting items from a list.
If you haven't read previous articles in this series, make sure to check them out.
https://joeljaison.hashnode.dev/mastering-conditional-rendering-and-lists-in-svelte
https://joeljaison.hashnode.dev/unlocking-the-power-of-svelte-mastering-bindings
https://joeljaison.hashnode.dev/getting-started-with-svelte-a-comprehensive-tutorial-series
Handling Click Events
Let's begin by tackling a common scenario: adding a button to each item in a list and deleting that item when the button is clicked.
<script>
import '../app.postcss'
let people = [
{ id: 1, name: 'Alice', phone: '123-456-7890', address: '123 Main St' },
{ id: 2, name: 'Charlie', phone: '789-123-4567', address: '789 Oak St' },
{ id: 3, name: 'Haris', phone: '982-123-4612', address: '789 SeaRoad ' },
];
let newPerson = {
name: '',
phone: '',
address: '',
};
function addPerson() {
const id = people.length + 1;
people = [...people, { id, ...newPerson }];
newPerson = { name: '', phone: '', address: '' };
}
</script>
<style>
.contact-form {
background: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
</style>
<div class="max-w-xl mx-auto">
<h1 class="text-3xl font-semibold mb-4 text-blue-600">Contact List</h1>
<div class="space-y-4">
{#each people as person (person.id)}
<div class="contact-item bg-blue-100 p-4 rounded-lg shadow-md flex justify-between items-center transition transform hover:scale-105">
<div class="contact-details">
<p class="text-xl font-semibold text-blue-800">{person.name}</p>
<p class="text-gray-600">Phone: {person.phone}</p>
<p class="text-gray-600">Address: {person.address}</p>
</div>
<button on:click={() => handleClick(person.id)} class="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded transition transform hover:scale-105">Delete</button>
</div>
{/each}
</div>
<!-- Input fields for adding new contacts -->
<div class="contact-form p-4 mt-4 bg-blue-100 rounded-lg shadow-md">
<h2 class="text-2xl font-semibold mb-2 text-blue-800">Add New Contact</h2>
<input type="text" placeholder="Name" bind:value={newPerson.name} class="border p-2 mb-2 rounded w-full" />
<input type="text" placeholder="Phone" bind:value={newPerson.phone} class="border p-2 mb-2 rounded w-full" />
<input type="text" placeholder="Address" bind:value={newPerson.address} class="border p-2 mb-2 rounded w-full" />
<button on:click={addPerson} class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-full focus:outline-none focus:shadow-outline transition transform hover:scale-105">Add Contact</button>
</div>
</div>
In this code, we've added a "Delete" button to each person in the list. The key part is the on:click
attribute, which specifies the event handler for a click event. We're using an inline function to call handleClick
and passing the person.id
as an argument.
Now, let's implement the handleClick
function:
function handleClick(id) {
people = people.filter(person => person.id !== id);
}
Here, we define handleClick
, which takes the id
of the person we want to delete. We use the filter
method to create a new array that excludes the person with the matching id
. Then, we update the people
array with the filtered result.
This approach ensures that the function isn't invoked automatically when the page loads. It only runs when the button is clicked, thanks to the inline function.
Additional Event Handling Examples
Handling Mouseover Events
In addition to click events, you can handle other events like mouseover
. Let's say you want to highlight a person's name when the mouse hovers over it:
{#each people as person (person.id)}
<div class="person-item">
<p class="name" on:mouseover={() => handleMouseOver(person.id)}>{person.name}</p>
<button on:click={() => handleClick(person.id)}>Delete</button>
</div>
{/each}
In this example, we've added an on:mouseover
event handler to the person's name. When the mouse hovers over it, we call the handleMouseOver
function, passing the person.id
as data.
Handling Form Submissions
Handling form submissions is a common use case in web development. Let's create a simple form that adds new people to our list:
<script>
let newPersonName = '';
</script>
<form on:submit={handleSubmit}>
<input type="text" bind:value={newPersonName} placeholder="Enter a name" />
<button type="submit">Add Person</button>
</form>
In this code, we've created a form with an on:submit
event handler that calls the handleSubmit
function when the form is submitted. We're also using bind:value
to capture the input value in real time.
function handleSubmit(event) {
event.preventDefault();
const newPerson = { id: people.length + 1, name: newPersonName };
people = [...people, newPerson];
newPersonName = '';
}
In the handleSubmit
function, we prevent the default form submission behavior, create a new person object with a unique ID, add it to the people
array, and clear the input field.
Eaxmple:
Let's put this knowledge into a real-world context. Imagine you have a list of people, and you want to provide a user-friendly way to remove them from the list.
<script>
let people = [
{ id: 1, name: 'Mario' },
{ id: 2, name: 'Luigi' },
{ id: 3, name: 'Yoshi' }
];
</script>
{#each people as person (person.id)}
<div class="person-item">
<p>{person.name}</p>
<button on:click={() => handleClick(person.id)}>Delete</button>
</div>
{/each}
In this example, we have a list of people with names and unique IDs. We use the same event-handling technique to delete individuals from the list.
Assignment #5
For your assignment, take the skills you've learned and expand upon them:
Create a new project or expand an existing one.
Implement a list of items (e.g., tasks, products, or contacts).
Add functionality to delete items from the list when a "Delete" button is clicked.
Experiment with different types of data and user interfaces to solidify your understanding.
Remember, practice is key to mastery. Don't hesitate to reach out for help or share your progress in the comments or via email.
Stay tuned for the next tutorial, where we'll explore event forwarding. Your journey to mastering JavaScript continues!
Thank you for reading and happy coding! ๐๐