Home Cooking
Today I practiced a home-cooked dish every developer knows: a todo list.
There are many ways to cook this dish. I stuck to the simplest ingredients you can grab at home and the most basic method. In this not-too-cold winter, I hope we junior developers can warm up together. The finished dish is at the bottom—free samples for everyone.
Recipe and steps:
- Clicking the button adds an item (
createElement()). - Put specific text into the new item (turn the input into a text node, then
.appendChildit into the list). - Carry the input field’s text into the new item (use
input.value). - Only add a new item if the input field has text.
- Listen for Enter to add an item too (
addEventListener("keypress", function); Enter’s keycode is 13). - Listen for clicks on the list and toggle a strikethrough style on the clicked item (
classList.toggle()). - When adding a new item, also include a button with it (create a delete button and add it to the list).
- Listen for different cases: text click toggles strikethrough; delete button removes the item (remove the parent with
target.parentElement.remove()). - When adding a new item, make sure the new delete button is also listened to (re-
querySelectorAllall items, then attach a listener to the last element).
A little garnish—watch these small details:
.appendChild’s argument must be an element, so text needscreateTextNodebefore it can go into the list.- Bundling the button with the new item means clicking the text for strikethrough also strikes through the button label. Fix: wrap the text in a
spanand only toggle strikethrough when the click target is thatspan. .addEventListenerlistens on parent and children together, so use.targetfor the child and.currentTargetfor the parent.- New list items’ delete buttons don’t work at first because the new button wasn’t being listened to—so when you add a list item, register the new button as a listener target.
- When you try to listen to the new button, you may not find it yet, so re-run
.querySelectorAllto refresh the selection of all buttons.
It turns out that even this everyday “home cooking” needs so many details for the diner. When we scroll Facebook or browse the web, we rarely think every page is a developer’s sweat—every button is hard-earned grain.
Try it: Home cooking: “reading list”