D3.js drag usage - d3.drag()

Explains D3 drag events.

Example program

Run code

Usage

D3 drag supports touch events.

d3.selectAll("div")
  .call(
      d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended)
  );


// Function called when dragging starts
function dragstarted(event) {
  // Processing
}

// Function called while dragging
function dragged(event) {
  // Processing
}

// Function called when dragging ends
function dragended(event) {
  // Processing
}

Run code

Specify the element to which you want to set the drag event in the "div" part. Internally, drag is registered as an event by the on(...) method.

If you want to remove the drag event, you can remove it as follows:

d3.selectAll("div")
  .on(".drag", null);

Event variables

When an event starts, the following event variables are registered in event.

target Reference to the object created with d3.drag().
type Drag operation type: start, drag, end.
subject Reference to the data object of the element related to the drag event.
x Current x coordinate
y Current y coordinate
dx Change amount of the x coordinate, not the total drag distance
dy Change amount of the y coordinate, not the total drag distance
identifier The string "mouse" or a numeric touch identifier.
active Number of currently active drag gestures.
sourceEvent The underlying input event for the drag event, such as mousemove or touchmove.

You can reference it with event.target inside functions such as dragstarted.

Correspondence with other events

The correspondence table for other events is shown below. Events are summarized into the three drag events: start, drag, and end.

Event Listening Element Drag Event Default Prevented?
mousedown selection start no
mousemove window drag yes
mouseup window end yes
dragstart window yes
selectstart window yes
click window yes
touchstart selection start no
touchmove selection drag yes
touchend selection end no
touchcancel selection end no

Reference site: d3-drag | GitHub

Summary

Touch events are supported automatically, so drag can work across multiple device types. D3 zoom events are also summarized here, so refer to them as well.