Reading history

JavaScript Project: Build a Kanban Board

9 min read Updated 0 views

Build a study Kanban board with state-then-render, event delegation, drag and drop, accessible move buttons and safe localStorage saving, with the full code.

In this project you will build a Kanban board for planning your studies: three columns, To do, Doing and Done, with cards you can add, move and delete. Cards can be dragged between columns or moved with arrow buttons, and the board remembers its state between visits. The project combines many recent lessons: event delegation, closest(), drag and drop, safe DOM building and localStorage, organised around one important idea: state first, then render.

In this project you will practise

  • Keeping data in one array and rebuilding the view from it
  • Delegated click and drag events on one container
  • Building cards safely with createElement and textContent
  • Accessible buttons as an alternative to dragging
  • Saving to localStorage with error handling

This project uses event delegation, drag and drop, DOM manipulation and localStorage.

The Complete App

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Study Kanban Board</title>
  <style>
    * { box-sizing: border-box; }
    body { font-family: system-ui, sans-serif; margin: 12px; font-size: 14px; background: #f5f7fa; color: #1f2933; }
    form { display: flex; gap: 6px; margin-bottom: 10px; }
    input, select, button { font: inherit; padding: 6px 8px; }
    input { flex: 1; min-width: 0; }
    .board { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
    .column { background: #e9eef4; border-radius: 8px; padding: 8px; min-height: 160px; }
    .column h3 { margin: 0 0 6px; font-size: 14px; display: flex; justify-content: space-between; }
    .column.over { outline: 2px dashed #1e88e5; }
    .card { background: #fff; border-radius: 6px; padding: 6px 8px; margin: 6px 0; cursor: grab;
            box-shadow: 0 1px 2px rgba(0,0,0,.12); display: flex; gap: 4px; align-items: center; }
    .card span { flex: 1; }
    .card button { padding: 0 6px; border: 0; background: none; cursor: pointer; font-size: 16px; }
    .card.dragging { opacity: .4; }
    @media (max-width: 520px) { .board { grid-template-columns: 1fr; } }
  </style>
</head>
<body>
  <form id="new-card">
    <input id="title" placeholder="New study task" maxlength="60" required>
    <button>Add</button>
  </form>
  <div class="board" id="board">
    <section class="column" data-status="todo"><h3>To do <small></small></h3><div class="cards"></div></section>
    <section class="column" data-status="doing"><h3>Doing <small></small></h3><div class="cards"></div></section>
    <section class="column" data-status="done"><h3>Done <small></small></h3><div class="cards"></div></section>
  </div>
  <script>
    var ORDER = ["todo", "doing", "done"];
    var KEY = "study-kanban";

    // ---- State: the single source of truth ----
    var cards = load() || [
      { id: 1, title: "Revise Physics chapter 3", status: "todo" },
      { id: 2, title: "Chemistry lab report", status: "doing" },
      { id: 3, title: "Maths exercise 2.1", status: "done" },
    ];
    var nextId = cards.reduce(function (max, c) { return Math.max(max, c.id); }, 0) + 1;

    function load() {
      try {
        var saved = JSON.parse(localStorage.getItem(KEY));
        return Array.isArray(saved) ? saved : null;
      }
      catch (e) { return null; }           // storage blocked or data broken
    }
    function save() {
      try { localStorage.setItem(KEY, JSON.stringify(cards)); }
      catch (e) { /* storage not available: keep working in memory */ }
    }

    // ---- Render: rebuild the board from the state ----
    function render() {
      document.querySelectorAll(".column").forEach(function (col) {
        var list = col.querySelector(".cards");
        var mine = cards.filter(function (c) { return c.status === col.dataset.status; });
        list.replaceChildren();
        mine.forEach(function (c) {
          var card = document.createElement("div");
          card.className = "card";
          card.draggable = true;
          card.dataset.id = c.id;
          var title = document.createElement("span");
          title.textContent = c.title;                    // user text: never innerHTML
          card.append(title);
          if (c.status !== "todo") card.append(makeButton("←", "left", "Move left"));
          if (c.status !== "done") card.append(makeButton("→", "right", "Move right"));
          card.append(makeButton("×", "delete", "Delete"));
          list.append(card);
        });
        col.querySelector("small").textContent = mine.length;
      });
      save();
    }
    function makeButton(text, action, label) {
      var b = document.createElement("button");
      b.textContent = text;
      b.dataset.action = action;
      b.setAttribute("aria-label", label);
      return b;
    }
    function find(id) {
      return cards.find(function (c) { return c.id === Number(id); });
    }

    // ---- Add ----
    document.getElementById("new-card").addEventListener("submit", function (e) {
      e.preventDefault();
      var input = document.getElementById("title");
      var text = input.value.trim();
      if (!text) return;
      cards.push({ id: nextId++, title: text, status: "todo" });
      input.value = "";
      render();
    });

    // ---- Buttons: one delegated listener for the whole board ----
    var board = document.getElementById("board");
    board.addEventListener("click", function (e) {
      var button = e.target.closest("button[data-action]");
      if (!button) return;
      var card = find(button.closest(".card").dataset.id);
      var i = ORDER.indexOf(card.status);
      if (button.dataset.action === "left") card.status = ORDER[i - 1];
      if (button.dataset.action === "right") card.status = ORDER[i + 1];
      if (button.dataset.action === "delete") cards = cards.filter(function (c) { return c !== card; });
      render();
    });

    // ---- Drag and drop, also delegated ----
    board.addEventListener("dragstart", function (e) {
      var card = e.target.closest(".card");
      if (!card) return;
      e.dataTransfer.setData("text/plain", card.dataset.id);
      card.classList.add("dragging");
    });
    board.addEventListener("dragend", function (e) {
      var card = e.target.closest(".card");
      if (card) card.classList.remove("dragging");
    });
    board.addEventListener("dragover", function (e) {
      var col = e.target.closest(".column");
      if (!col) return;
      e.preventDefault();
      document.querySelectorAll(".column.over").forEach(function (c) { if (c !== col) c.classList.remove("over"); });
      col.classList.add("over");
    });
    board.addEventListener("drop", function (e) {
      var col = e.target.closest(".column");
      if (!col) return;
      e.preventDefault();
      col.classList.remove("over");
      var card = find(e.dataTransfer.getData("text/plain"));
      if (card) { card.status = col.dataset.status; render(); }
    });

    render();
  </script>
</body>
</html>

Result

Save the code as kanban.html and open it in your browser. Add a few tasks, move them around, then reload the page: they are still there. In the live demo above, the frame blocks storage, so changes are lost on reload, but everything else works.

Step 1: State and Rendering

  • The cards array is the single source of truth. Each card is a plain object with an id, a title and a status.
  • Every action follows the same pattern: change the array, then call render(). The code never moves card elements by hand, so the page cannot get out of step with the data.
  • render() empties each column with replaceChildren() and rebuilds its cards from the array, then updates the counts and saves. For a board of this size, rebuilding is fast and keeps the code simple.
  • nextId starts one above the largest saved id, so new cards never clash with old ones.

Step 2: Building Cards Safely

  • The title goes in with textContent, so a task named <img onerror=…> is shown as text instead of running code.
  • Buttons get a data-action attribute and an aria-label. The arrow characters alone would be read aloud as “rightwards arrow”, which is not helpful; the label says “Move right”.
  • Cards in To do have no left button and cards in Done have no right button, so a status can never move past the ends of ORDER.

Step 3: Delegated Events

  • One click listener on the board handles every button on every card, including cards created later. closest("button[data-action]") finds the button, and closest(".card") finds its card’s id.
  • Moving left or right changes the status to the previous or next entry in ORDER. Deleting filters the card out of the array.
  • Drag events are delegated too. dragstart stores the card id, dragover calls preventDefault() on columns to allow dropping and highlights the column, and drop updates the status and re-renders.
  • The arrow buttons make the board fully usable with a keyboard or on phones where dragging is awkward.

Step 4: Saving Safely

  • save() stores the array as JSON after every render. load() reads it back and checks with Array.isArray that the data really is a list.
  • Both are wrapped in try...catch. Storage can be blocked by privacy settings or sandboxed frames like the demo above, and saved text could be damaged. In those cases the app falls back to the starting cards instead of crashing.

Ideas to Extend the Project

  1. Double-click a card’s title to edit it, using a prompt or an inline input.
  2. Add a due date to each card and highlight overdue ones in red.
  3. Add a “Clear done” button that removes every card in the Done column.
  4. Allow reordering inside a column by dropping a card above or below another.

Common Mistakes

  1. Changing the page and the data separately, so they slowly drift apart. Change the data, then render.
  2. Adding listeners to each card inside render(), which is easy to get wrong; delegation avoids it.
  3. Using innerHTML with task titles, which allows script injection.
  4. Comparing ids of different types: dataset.id is a string, so convert it with Number() before comparing with the numeric ids.

Practice Exercises

Exercise 1. Add a “Clear done” button that deletes all finished cards.

Show answer
// HTML: <button id="clear-done" type="button">Clear done</button>
document.getElementById("clear-done").addEventListener("click", function () {
  cards = cards.filter(function (c) { return c.status !== "done"; });
  render();
});

Exercise 2. Show the percentage of cards that are done in the page title, for example “Study board (33% done)”.

Show answer
// at the end of render()
var done = cards.filter(function (c) { return c.status === "done"; }).length;
var pct = cards.length ? Math.round(done / cards.length * 100) : 0;
document.title = "Study board (" + pct + "% done)";

Frequently Asked Questions

Is rebuilding the whole board on every change slow?

Not for a few hundred cards: the browser handles it in a few milliseconds. Frameworks such as React and Vue use the same state-then-render idea, but compare old and new views so that only the changed parts are updated.

How would several people share one board?

The cards would be stored on a server instead of in localStorage. Each change would be sent with fetch, and other users would receive updates by polling or through a live connection such as WebSockets.

Summary

  • Keep all data in one array and rebuild the view from it after every change.
  • One delegated listener handles clicks and drags for every card.
  • Build elements with textContent and give icon buttons aria-labels.
  • Wrap localStorage in try...catch and validate what you load.

Next: JavaScript Recursion.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *