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.
Write an app that lets the user add an item to a todo list.
In this version you'll learn the following skills:
If you need to brush up on arrays, read the declaration section of this guide before starting.
<script>
let tasks = []
function addTask() {
tasks = [...tasks, '']
}
</script>
let tasks = []
creates an array. This will be where all the tasks are stored.
The addTask
function overwrites the existing tasks array with a new array that has all the previous tasks, plus one blank one. The [ ]
creates a new array, then ...tasks
gets all the previous tasks, and ' '
adds a blank one at the end.
<style>
.task {
display: block;
}
</style>
The .task
class is the only CSS we will use in this whole project. It simply puts each task on a new line.
<button on:click={addTask}>📝 Add</button>
{#each tasks as task, index}
<div class="task">
<input bind:value={tasks[index]}>
</div>
{/each}
The Add button is a regular HTML button that uses Svelte's on:click
to run the addTask
function when it's clicked.
The last section is a Svelte each
loop that goes through all of the tasks in the tasks
array. Each input
is linked to a task with Svelte's bind:value
.
Whenever an input gets changed by the user, that task in the array will get updated in real time.
The div
is just there so that we can use the .task
CSS class to put each task on its own line.
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.
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.