Skip to main content
100%

Click vs. (a great deal of) Drag(ging)

✓ Published0🌍 Public
HHerst
Last edited Feb 19, 2018
Created on Feb 3, 2018

Twenty colored circles are rendered in an SVG, where each circle can be either clicked or dragged. A click triggers a two-step radius animation (expanding to 64, then shrinking back to 32), while dragging moves the circle and, once the drag exceeds a small threshold, brings the circle to the front using `raise()` and adds an active class. The example uses D3 v4’s `d3.drag()` with `.clickDistance(4)` to distinguish clicks from drags, alongside manual checks on `sourceEvent` coordinates to handle edge cases where the drag ends near the start point. Data is generated randomly as an array of 20 `{x, y}` objects, with colors assigned via `d3.scaleOrdinal` and `d3.schemeCategory20`.

AI-generated description

Here .clickDistance() is used together with some manual checking to do certain stuff like calling .raise() only outside the distance otherwise the click event might not get triggered (because the element got removed from the DOM before release of the mouse button).

Related to https://bl.ocks.org/mbostock/22994cc97fefaeede0d861e6815a847e (this one it is based on), https://bl.ocks.org/mbostock/a84aeb78fea81e1ad806 (unlike that example this here allows for a tiny bit of movement → unstable clicks). See also the discussion at https://github.com/d3/d3-drag/issues/48 to make the need for additional manual checking go away.

gpl-3.0 Licensed

Similar vizzes