Todo List v2

Deleting from the list.

Skills: InputOutputVariablesIf StatementsLoops
0.5%

Version 2 Brief

Add a button to each task that lets the user remove it.

In this version you'll learn the following skills:

  • Create a function that requires a parameter
  • Remove an item from an array
  • Link a button to a function and send it a parameter

If you need to brush up on function parameters, read the parameter section of this guide before starting.

Script

function removeTask(index) {
    tasks = [
        ...tasks.slice(0, index),
        ...tasks.slice(index + 1)
    ]
}

The removeTask function has index in brackets after it, which means it is expecting to be told which item to remove. index will be a number that represents an item in the tasks array, for example if index is 3 then the item to be removed is tasks[3] (the fourth item).

Similarly to addTask, this function overwrites the previous array with a new one that is missing the item to be removed. It does this by slicing the old tasks array into two pieces: one with all the items up to index, and one with all the items after index.

You can read more about slice on this guide.

Markup

{#each tasks as task, index}
    <div class="task">
    <input bind:value={tasks[index]}>
    <button on:click={() => { removeTask(index) }}>🗑</button>
    </div>
{/each}

Each task now comes with a button to remove it. The button is bound to the removeTask with the same on:click feature used in version 1 for the Add button.

The difference is that this button needs to tell the function which item to remove. To do this, the button has to include the index when it calls the function. It would be good to be able to simply write on:click={removeTask(index)} but unfortunately Svelte is not capable of doing this. Instead, we have to wrap the removeTask(index) in some more brackets, namely () => { removeTask(index) }.

Luckily, when you want to send a function some information from a button click it's always the same as this.


You can use the Svelte code below if you need help to get started. It contains everything you need for this program.

If you can, try to complete the project without looking at it.


Sandbox

Feel free to play around with the example below to see how the web page reacts to your code changes in a consequence-free environment. You won't break or overwrite anything so go for gold.