Open in a new tab

Drag cards between two lists with Pointer Events (mouse, pen, touch), a hover mark on the target list, and a button on every card that moves it without dragging.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Boards, playlists and sortable groups: items that move between containers inside the page. For files dragged in from the operating system, see fw/dom-file-intake.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html, main.js and style.css next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

What it shows

  • dnd.draggable(el, { data, handle }): a drag starts past a 5 px threshold on the handle (the card's text); data() names what is dragged.
  • dnd.dropTarget(el, { accept, onDrop, hoverClass }): the list under the pointer at release receives the data; hoverClass marks it while a card is over it.
  • Pointer Events, not the HTML5 drag API, so touch and pen work too; touch-action: none on the handle keeps the page from scrolling instead, and user-select: none keeps the drag from selecting its text.
  • The ghost under the pointer is a clone of the card, appended to the body and faded out after the drop; style.css gives it a width.
  • A drag-only interface fails WCAG 2.5.7 (Dragging Movements): every card also has a button that moves it, by keyboard or with one click. Both paths end in the same moveCard.

Code

main.js

javascriptApache-2.052 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { dnd } from '@awacloud/fw/dom/query/dnd.js';

fw.runtime.registerAllDeep([dnd]);
const DND = fw.runtime.resolve('dnd');

/** The two columns: list id → its heading, as the move button names it. */
const COLUMNS = { todo: 'To do', done: 'Done' };
const status = /** @type {HTMLElement} */ (document.getElementById('status'));

/**
 * Move a card to a column, and say so. Dragging and the button both end here.
 * @param {HTMLElement} card @param {'todo' | 'done'} to
 */
function moveCard(card, to) {
    /** @type {HTMLElement} */ (document.getElementById(to)).appendChild(card);
    const other = to === 'todo' ? 'done' : 'todo';
    /** @type {HTMLElement} */ (card.querySelector('button')).textContent = `Move to ${COLUMNS[other]}`;
    status.textContent = `"${card.querySelector('span')?.textContent}" moved to ${COLUMNS[to]}`;
}

/** A card: its text, and a button that moves it (the alternative to dragging, WCAG 2.5.7). @param {string} text */
function createCard(text) {
    const card = document.createElement('li');
    card.className = 'card';
    card.append(Object.assign(document.createElement('span'), { textContent: text }), document.createElement('button'));
    const button = /** @type {HTMLButtonElement} */ (card.querySelector('button'));
    button.type = 'button';
    button.textContent = 'Move to Done';
    button.addEventListener('click', () => moveCard(card, card.parentElement?.id === 'todo' ? 'done' : 'todo'));
    // Pointer Events drag: the data names the card; the button is the drag-free path.
    DND.draggable(card, { data: () => ({ text }), handle: 'span' });
    return card;
}

// Each list accepts a card from the other one; the hover class marks the target.
for (const id of /** @type {('todo' | 'done')[]} */ (['todo', 'done'])) {
    const list = /** @type {HTMLElement} */ (document.getElementById(id));
    DND.dropTarget(list, {
        hoverClass: 'drop-here',
        accept: (/** @type {{ text?: string }} */ data) => typeof data?.text === 'string',
        onDrop: (/** @type {{ text: string }} */ data) => {
            const cards = [...document.querySelectorAll('.card')];
            const card = cards.find((c) => c.querySelector('span')?.textContent === data.text);
            if (card && card.parentElement !== list) moveCard(/** @type {HTMLElement} */ (card), id);
        },
    });
}

/** @type {HTMLElement} */ (document.getElementById('todo'))
    .append(...['Write the README', 'Run the tests', 'Ask for a review'].map(createCard));

index.html

htmlApache-2.027 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Drag cards between two lists</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <link rel="stylesheet" href="./style.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Drag cards between two lists</h1>
    <p>Drag a card by its text, or use its button.</p>
    <div class="board">
      <section aria-labelledby="todo-title"><h2 id="todo-title">To do</h2><ul id="todo"></ul></section>
      <section aria-labelledby="done-title"><h2 id="done-title">Done</h2><ul id="done"></ul></section>
    </div>
    <p id="status" role="status"></p>
  </main>
</body>
</html>

style.css

cssApache-2.024 lines

/* SPDX-License-Identifier: Apache-2.0 */
.board { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: 1rem; }
.board ul {
    list-style: none;
    padding: 0.5rem;
    margin: 0;
    min-height: 8rem;
    border: 1px dashed var(--ex-border, #ccc);
    border-radius: 8px;
}
.board ul.drop-here { outline: 3px solid var(--ex-accent, #2563eb); }
.card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem;
    margin-block: 0.25rem;
    border: 1px solid var(--ex-border, #ccc);
    border-radius: 6px;
}
.card span { cursor: grab; touch-action: none; flex: 1; }
/* The drag preview: fw clones the card onto the body at its size; the list's background does not follow it. */
body > .card { background: var(--ex-surface, #fff); }