Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Captured pointer drags: commit or roll back

Keep the drag preview separate from the committed value, and settle the drag only once even when capture loss follows release.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

let drag = null;

// beginDrag saves the pointer ID and a snapshot, then captures the pointer.
// updatePreview changes only the preview for the matching pointer ID.
element.addEventListener('pointerdown', beginDrag);
element.addEventListener('pointermove', updatePreview);
element.addEventListener('pointerup', (event) => settle(event, true));
element.addEventListener('pointercancel', (event) => settle(event, false));
element.addEventListener('lostpointercapture', (event) => settle(event, false));

function settle(event, commit) {
  if (drag === null || event.pointerId !== drag.pointerId) return;
  const current = drag;
  drag = null;
  if (commit) commitPreview(current);
  else restoreSnapshot(current);
}

Treat a captured drag as a transaction. On pointerdown, save the starting value and pointerId, then call element.setPointerCapture(event.pointerId) so later events for that pointer reach the element even outside its bounds. Matching pointermove events update only the preview. Movement can also occur while hovering; a move can report a change such as pressure, and the browser can coalesce several movement samples into one event.

Commit the preview only on pointerup. Restore the starting value on pointercancel, for example when the browser takes over to scroll, or on lostpointercapture if the drag is still active. In the shared finalizer, match the pointer ID and clear the active drag before applying either outcome. That makes capture loss after pointerup or pointercancel a no-op for the result. Capture and dragging have separate lifetimes: losing capture does not mean the pointer was released.

Direct touch can trigger implicit capture. setPointerCapture() throws NotFoundError if the ID does not match an active pointer. Use releasePointerCapture() to give up capture early; the browser releases it automatically after pointerup or pointercancel. Set CSS touch-action before the gesture and limit touch-action: none to the area that needs it, since it can block touch zoom.

These events use the browser’s PointerEvent Web API and do not require ECMAScript 2024. For touch or pen-tip contact, pointerdown and pointerup mark contact and lift-off. For a mouse, they mark the first button press and the last button release, not each individual press or release as mousedown and mouseup do.

Examples

const assert = require('node:assert/strict');
const { chromium } = require('playwright');

async function main() {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage({ viewport: { width: 480, height: 240 } });
    page.on('console', (message) => {
      if (message.type() === 'log') console.log(message.text());
    });
    await page.setContent(`
      <div id="pad" style="position:fixed;top:16px;left:16px;box-sizing:border-box;
        width:180px;height:84px;padding:16px;background:#def;color:#123;
        touch-action:none;user-select:none">Press here, move outside, then release</div>
      <output id="position" data-committed="0"
        style="position:fixed;top:116px;left:16px">0</output>
    `);

    await page.evaluate(() => {
      const pad = document.querySelector('#pad');
      const position = document.querySelector('#position');
      let committed = 0;
      let drag = null;
      let capturedId = null;

      pad.addEventListener('pointerdown', (event) => {
        if (!event.isTrusted || event.button !== 0 || capturedId !== null) return;
        pad.setPointerCapture(event.pointerId);
        capturedId = event.pointerId;
        drag = {
          pointerId: event.pointerId,
          startX: event.clientX,
          snapshot: committed,
          preview: committed,
          loggedMove: false
        };
        console.log(event.type);
      });

      pad.addEventListener('pointermove', (event) => {
        if (drag === null || event.pointerId !== drag.pointerId) return;
        drag.preview = drag.snapshot + event.clientX - drag.startX;
        position.textContent = String(drag.preview);
        if (!drag.loggedMove) {
          drag.loggedMove = true;
          console.log(event.type);
        }
      });

      function settle(event, commit) {
        if (drag === null || event.pointerId !== drag.pointerId) return false;
        const current = drag;
        drag = null;
        if (commit) committed = current.preview;
        position.dataset.committed = String(committed);
        position.textContent = String(commit ? committed : current.snapshot);
        return true;
      }

      pad.addEventListener('pointerup', (event) => {
        if (settle(event, true)) console.log(event.type);
      });
      pad.addEventListener('pointercancel', (event) => {
        if (settle(event, false)) console.log(event.type);
      });
      pad.addEventListener('lostpointercapture', (event) => {
        if (event.pointerId !== capturedId) return;
        capturedId = null;
        settle(event, false);
        console.log(event.type);
      });
    });

    // Drive Chromium's mouse rather than dispatching synthetic pointer events.
    await page.mouse.move(40, 40);
    await page.mouse.down();
    await page.mouse.move(320, 40);
    await page.mouse.move(340, 40);

    const position = page.locator('#position');
    assert.equal(await position.textContent(), '300');
    assert.equal(await position.getAttribute('data-committed'), '0');

    await page.mouse.up();
    assert.equal(await position.getAttribute('data-committed'), '300');
    assert.equal(await position.textContent(), '300');
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Result

pointerdown
pointermove
pointerup
lostpointercapture

Run the Node.js and Playwright example as described in the verification instructions. Playwright presses inside the panel, moves the mouse outside it, and releases there. Only the first matching move is logged. The expected output covers normal completion, not cancellation or early capture loss.

Related lessons

  • JavaScript · Lesson 35 · Advanced · Version: 4

Sources