Skip to main content
100%

d3.drag with grouped elements in v4

✓ Published0🌍 Public
Dd3noob
Last edited Aug 13, 2016
Created on Aug 13, 2016

This example demonstrates how to use d3.drag in D3 v4 to drag grouped SVG elements together. Ten rectangles with accompanying text labels are generated randomly and placed on a 960×500 SVG canvas. The drag behavior is attached to each `<g>` group, and during the drag event both the rectangle and text are updated simultaneously using `d3.event.x` and `d3.event.y`. The code uses D3 v4’s selection, scaleOrdinal with `schemeCategory20`, and the d3-drag module.

AI-generated description

The resulting code (with some minor formatting alterations) from an answer on Stack Overflow to a question about how to group two elements and drag them using d3.drag.

Kudos (and thanks) to Dragon_Slayer for the solution.

A block for the original (not working correctly) code is here.

Similar vizzes