Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 56 ยท Projects

Project: To-Do List

Build a to-do list in jQuery: add, complete and delete tasks, filter with event delegation, count what is left and animate items, all from in-memory state.

A to-do list is the classic first real application, and it earns that place: it needs forms, lists that change over time, events on elements that did not exist when the page loaded, and a few small decisions about where data lives. Those are exactly the situations where jQuery habits either help or hurt.

You will build it in two steps. First a minimal version that adds tasks, ticks them off and counts what is left, so the data flow is clear. Then the full app with delete animations, filters and a "clear completed" button. The state lives in a plain JavaScript array; saving it to localStorage is left out because the lesson sandbox blocks storage, but the final section shows exactly where to add it on your own site.

Design first

State An array of {id, text, done} objects.
Render One function draws the list from state.
Events Delegated handlers change state, then render.

The DOM shows the state; it is never the source of truth.

1 / 2

Keep the data separate from the page

The beginner approach reads the page to find out what is on the list: count the li elements, check whether each has a class. It works for ten minutes and then breaks, because every feature (filter, counter, undo) has to untangle the DOM. The cleaner design keeps an array of task objects, and a single render() function that turns the array into list items. Every event handler follows the same three steps: change the array, call render(), move focus if needed.

The render() function removes everything and rebuilds the list. That sounds wasteful, but for a few hundred items it is instant, and it removes a whole class of bugs where the page and the data disagree. Items are created with $("<li>") and .text(), never with string concatenation, so a task named <b>Buy milk</b> appears as typed (see best practices).

Step 1: add, complete and count

This version covers the core loop. Notice what is not here: no handler is attached to an individual li. The change handler lives on the list and uses delegation, so tasks added later work without any rebinding.

Step 1: add, tick and count

Three details are worth a second look. The data-id attribute on each li is the link back to the state: .closest("li").data("id") finds the task for any click, and .data() returns a number, matching the numeric id. The status line has role="status", so screen readers announce the new count politely. And event.preventDefault() stops the form from reloading the page, as in the form validation lesson.

Step 2: delete, filter and clear

Now add the remaining features. Each one follows the same pattern, which is the point: adding a feature means adding one handler and, sometimes, a field of state.

  • Filter. A filter variable holds "all", "active" or "done". render() draws only matching tasks, and the filter buttons carry aria-pressed so assistive technology knows which one is on.
  • Delete. The delete button slides its row up with .slideUp() and removes the task from the array in the animation callback. Removing it from the data first would re-render at once and cut the animation short. Checking .is(":animated") ignores a second click on a row that is already leaving.
  • Fade in new tasks. render() remembers which id was just added and animates only that row, so older items do not flash.
  • Clear completed. One filter call removes every finished task and disables the button when there is nothing to clear.
  • Empty state. When the visible list is empty, a message says so, which is friendlier than a blank space.
Step 2: the complete to-do list

Ideas for taking it further

Try these on your own; each one is a short, self-contained change.

  1. Persistence. On your own site, call localStorage.setItem("todos", JSON.stringify(todos)) at the end of render() and read it back with JSON.parse() at startup, wrapped in try/catch. The lesson sandbox blocks storage, so the code here keeps everything in memory.
  2. Editing. On dblclick of a label, swap it for a text input and commit on blur or Enter, cancelling on Escape.
  3. Keyboard. Make Delete work on the Delete key when a row has focus, and move focus to the next row after removing one so keyboard users do not lose their place.
  4. Drag to reorder. Combine the array with jQuery UI's sortable (see Using Plugins and jQuery UI) and update the array in its update event.
  5. A shared module. Turn the app into a plugin, as in Writing Your Own Plugin, so one page can host two independent lists.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does this project keep an array of tasks instead of reading the list items from the page?

    When the data is the source of truth and render() draws it, every feature works on clean data. Reading state back out of the page gets messier with each feature.
  2. 2. Why is the change handler attached to the ul with a ".toggle" selector?

    render() empties and recreates the items. A delegated handler lives on the surviving ul, so it keeps working for every new checkbox.
  3. 3. Why is the task removed from the array inside the .slideUp() callback?

    If the array changed first and render() ran immediately, the row would vanish without the animation. The callback runs when the animation finishes.
  4. 4. How does the app display a task named <b>Buy</b> safely?

    .text() writes characters rather than markup, so a task containing tags cannot inject HTML into the page.
  5. 5. What is the purpose of role="status" on the counter text?

    A status region is a polite live region, so assistive technology reads out changes such as "2 tasks left" without moving focus.

Summary

  • Store tasks in an array and let one render() function draw them; handlers change the data, then call render().
  • Use delegated handlers on the list so rebuilt or newly added items need no rebinding, and link rows to data with data-id and .data().
  • Build elements with $("<li>") and .text() so user text can never become markup.
  • Run the data change inside the .slideUp() callback so the animation can finish, and guard against repeat clicks with :animated.
  • Track filter state in a variable, mirror it with aria-pressed, and show an empty state.
  • Add live regions and aria-labels so the app works for screen reader users too.

Up next: Project: Image Gallery and Lightbox.