Build a to-do list

INPUT · Slides

Let Enter add it too

01 / 03

Reaching for the button gets old

In the last step you had to press the button every single time. On a phone especially, you want to just confirm and be done once you have typed.

Wrap the text box in a form and pressing Enter (or the confirm key on a phone) does the same thing as pressing Add.

<form id="form" class="row">  <input id="task">  <button id="add">Add</button></form>

02 / 03

Except now the page wipes itself

A form has a job of its own: send its contents to a server and reload the page. That rule dates back to when every site had a contact form on it.

So if you just wrap it and try, the list you built vanishes in an instant. It is not gone — the page reloaded and you are looking at a blank one.

03 / 03

Telling it to skip its usual job

The way to stop it is event.preventDefault() — literally do not do the default thing for this event.

You call it on the event you get handed on submit. That one line stops the reload and leaves only the code you wrote running.

form.addEventListener("submit", (event) => {  event.preventDefault()  // your own work starts here})