Skip to content
jshacks.dev
Browser

Build a Kanban Board With Drag and Drop in Vanilla JavaScript

Build a kanban board with drag and drop in vanilla JavaScript using the Drag and Drop API, drop positions, localStorage and a keyboard-accessible move option.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, Google Chrome, NGINX and GraphQL logos.

A kanban board is columns of cards that you move from left to right as work progresses. It is a good project because drag and drop touches state, the DOM and accessibility at once, and the native HTML Drag and Drop API gives you most of the behavior without a library. This post builds a kanban board with drag and drop in vanilla JavaScript: three columns, cards you can add, drag between and within columns, a visible drop position, persistence in localStorage and, importantly, a keyboard alternative, because the native drag events cannot be operated without a mouse. You will see how dragstart, dragover and drop fit together, why dragover must call preventDefault(), how to work out where to insert a card from the pointer position and how to keep the data model and the page in step. The API is documented on MDN.

The data model

Keep the board as plain data and treat the page as a rendering of it. Each column has an id, a title and an ordered list of cards.

model.jsJavaScript
export function createBoard() {
  return {
    columns: [
      { id: "todo", title: "To do", cards: [{ id: "c1", text: "Write the outline" }] },
      { id: "doing", title: "Doing", cards: [] },
      { id: "done", title: "Done", cards: [] },
    ],
  };
}

export function moveCard(board, cardId, toColumnId, toIndex) {
  let moved = null;
  const columns = board.columns.map((column) => {
    const cards = column.cards.filter((card) => {
      if (card.id === cardId) {
        moved = card;
        return false;
      }
      return true;
    });
    return { ...column, cards };
  });
  if (!moved) return board;

  return {
    columns: columns.map((column) => {
      if (column.id !== toColumnId) return column;
      const cards = [...column.cards];
      cards.splice(Math.min(toIndex, cards.length), 0, moved);
      return { ...column, cards };
    }),
  };
}

let board = createBoard();
board = moveCard(board, "c1", "doing", 0);
console.log(board.columns.map((c) => `${c.id}:${c.cards.length}`).join(" "));
Text
todo:0 doing:1 done:0

moveCard is a pure function: it removes the card from wherever it is, then inserts it into the target column at an index, and returns a new board. Because the removal happens before the insertion, an index computed from the page after the dragged card is hidden or removed still lands in the right place when you move a card within the same column.

The markup and rendering

Each column is a <section> with a list, and each card is a list item with draggable="true". Rendering builds them from the model.

index.htmlHTML
<main>
  <h1>Board</h1>
  <form id="add">
    <label for="text">New card</label>
    <input id="text" required autocomplete="off">
    <button type="submit">Add to To do</button>
  </form>
  <div id="board"></div>
  <p id="status" role="status" aria-live="polite"></p>
</main>
<script type="module" src="app.js"></script>
render.jsJavaScript
const boardEl = document.querySelector("#board");

export function render(board) {
  boardEl.replaceChildren();

  for (const column of board.columns) {
    const section = document.createElement("section");
    section.className = "column";
    section.dataset.column = column.id;

    const heading = document.createElement("h2");
    heading.textContent = `${column.title} (${column.cards.length})`;

    const list = document.createElement("ul");
    list.className = "cards";
    list.dataset.column = column.id;

    for (const card of column.cards) {
      const li = document.createElement("li");
      li.className = "card";
      li.draggable = true;
      li.dataset.id = card.id;
      li.tabIndex = 0;
      li.textContent = card.text;
      list.append(li);
    }

    section.append(heading, list);
    boardEl.append(section);
  }
}
Text
(three columns with headings that show the count; each card is draggable and focusable)

textContent keeps card text from being parsed as HTML. The cards get tabindex="0" so keyboard users can reach them, which the keyboard move feature below relies on.

Start a drag

The dragstart event fires on the card being dragged. Store its id in the event's dataTransfer, and mark the card so it can be styled.

dragstart.jsJavaScript
boardEl.addEventListener("dragstart", (event) => {
  const card = event.target.closest(".card");
  if (!card) return;
  event.dataTransfer.setData("text/plain", card.dataset.id);
  event.dataTransfer.effectAllowed = "move";
  requestAnimationFrame(() => card.classList.add("dragging"));
});

boardEl.addEventListener("dragend", (event) => {
  event.target.closest(".card")?.classList.remove("dragging");
  document.querySelectorAll(".over").forEach((el) => el.classList.remove("over"));
});
Text
(the dragged card dims while it is being moved and returns to normal when the drag ends)

Adding the dragging class inside requestAnimationFrame matters. If you change the card's appearance synchronously in dragstart, the browser may capture the changed element as the drag image, producing a faded ghost. Waiting one frame lets the browser take its snapshot first. Firefox also requires that something be set with setData for a drag to begin at all.

Allow dropping

Drop targets are opt-in. By default, an element is not a valid drop zone, and the browser shows the "not allowed" cursor. To make a column accept a drop, its dragover handler must call preventDefault().

dragover.jsJavaScript
boardEl.addEventListener("dragover", (event) => {
  const list = event.target.closest(".cards");
  if (!list) return;
  event.preventDefault();
  event.dataTransfer.dropEffect = "move";
  list.classList.add("over");
});

boardEl.addEventListener("dragleave", (event) => {
  const list = event.target.closest(".cards");
  if (list && !list.contains(event.relatedTarget)) list.classList.remove("over");
});
Text
(a column highlights while a card is dragged over it and the cursor shows a move)

The dragleave check avoids flicker: moving the pointer from the list onto a card inside it fires dragleave on the list, but relatedTarget is a child, so the highlight stays. This is the most common source of "my drop zone blinks" bugs.

Work out where to insert

When the card is dropped, you need an index. Find the first card in the list whose vertical midpoint is below the pointer, and insert before it. If none, the card goes at the end.

position.jsJavaScript
function dropIndex(list, clientY) {
  const cards = [...list.querySelectorAll(".card:not(.dragging)")];
  const index = cards.findIndex((card) => {
    const box = card.getBoundingClientRect();
    return clientY < box.top + box.height / 2;
  });
  return index === -1 ? cards.length : index;
}

const list = document.querySelector(".cards");
console.log(typeof dropIndex(list, 0));
Text
number

Excluding the dragging card from the measurement means the index refers to the list without it, which is exactly what moveCard expects after it removes the card. If your cards are in a horizontal or wrapping layout, compare on the horizontal axis, or pick the nearest card by distance.

Handle the drop

On drop, read the id, compute the index, update the model and re-render. Call preventDefault() here too, or Firefox may try to navigate to the dropped text.

drop.jsJavaScript
import { moveCard } from "./model.js";
import { render } from "./render.js";
import { save } from "./storage.js";

boardEl.addEventListener("drop", (event) => {
  const list = event.target.closest(".cards");
  if (!list) return;
  event.preventDefault();

  const id = event.dataTransfer.getData("text/plain");
  const index = dropIndex(list, event.clientY);
  board = moveCard(board, id, list.dataset.column, index);
  save(board);
  render(board);
  document.querySelector("#status").textContent = "Card moved.";
});
Text
(the card appears in the new column at the pointer position and the status says "Card moved.")

Re-rendering after every drop keeps the page identical to the data. The status paragraph is a live region, so screen reader users hear that something changed.

Save and load

Persist the board so it survives a reload. Guard against missing or broken data.

storage.jsJavaScript
const KEY = "kanban-v1";

export function load(fallback) {
  try {
    const raw = localStorage.getItem(KEY);
    const data = raw ? JSON.parse(raw) : null;
    return data && Array.isArray(data.columns) ? data : fallback;
  } catch {
    return fallback;
  }
}

export function save(board) {
  try {
    localStorage.setItem(KEY, JSON.stringify(board));
  } catch {
    // storage unavailable: the board lasts for this page view
  }
}

save({ columns: [] });
console.log(load(null).columns.length);
Text
0

A keyboard alternative

Native drag and drop does not work with a keyboard or most touch screens, and a board you can only use with a mouse fails accessibility requirements. Add a way to move the focused card with keys. A simple, discoverable scheme is Alt plus the arrow keys.

keyboard.jsJavaScript
boardEl.addEventListener("keydown", (event) => {
  const card = event.target.closest(".card");
  if (!card || !event.altKey) return;

  const columns = board.columns.map((c) => c.id);
  const from = card.closest(".cards").dataset.column;
  const fromIndex = columns.indexOf(from);
  const position = [...card.parentElement.children].indexOf(card);

  let target = null;
  if (event.key === "ArrowRight") target = [columns[fromIndex + 1], 0];
  if (event.key === "ArrowLeft") target = [columns[fromIndex - 1], 0];
  if (event.key === "ArrowUp") target = [from, position - 1];
  if (event.key === "ArrowDown") target = [from, position + 1];
  if (!target || target[0] === undefined || target[1] < 0) return;

  event.preventDefault();
  board = moveCard(board, card.dataset.id, target[0], target[1]);
  save(board);
  render(board);
  boardEl.querySelector(`[data-id="${card.dataset.id}"]`)?.focus();
  document.querySelector("#status").textContent = `Moved to ${target[0]}.`;
});
Text
(Alt+Right moves the focused card to the next column and keeps focus on it)

Restoring focus after the re-render is essential: rebuilding the DOM destroys the focused element, so the code finds the new element for the same id and focuses it. Add a line of help text that explains the shortcut. For touch devices, consider a "Move to" menu on each card, because mobile browsers support the native drag events poorly or not at all, and pointer events with your own drag logic are the robust choice there.

Practical notes

Styling matters for usability. Give each list a minimum height so an empty column is still a valid target, mark the over state clearly and show where the card will land, for example with a thin line. Keep card text from overflowing with overflow-wrap: anywhere. If cards are added to a long list, scroll the column, not the page, and note that dragging near the edge of a scrolling container does not auto-scroll in every browser, so test long columns.

Be careful with images and links inside cards. They are draggable by default, and a drag that starts on a link drags the URL, not the card. Set draggable="false" on them, or move the handle to a dedicated grip element. Finally, consider conflicts: if two tabs edit the same board, the last save wins, and the storage event lets one tab refresh when another saves.

Testing the board

Test the model first, because it is pure and needs no browser. Call moveCard with a card that moves within the same column to a lower index, to a higher index, to the end and to an empty column, and check the order each time. Moving to the same position should leave the board equal in content. Moving an unknown id should return the board unchanged, which the early return in the function guarantees.

Then test the interface. Drag a card across all three columns, drop it between two others, drop it on the empty space of an empty column and drop it outside any column, which must do nothing and leave the card where it was. Reload and confirm the board comes back from storage. Finally, use only the keyboard: focus a card with Tab, move it with Alt and the arrows, and confirm that focus stays on the card and the status message is read aloud by a screen reader. If any of these fail, fix the model or the handler that owns that behavior, not the symptom in the page.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.