HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Using d3.drag() to enable dragging on an SVG group

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enablegroupdragsvgusingdragging

Problem

I'm using the following function to enable dragging on an SVG group.

var dragcontainer = d3.drag()
                        .on("start", function () { })
                        .on("drag", function (d, i) {

                            this.x = this.x || 0;
                            this.y = this.y || 0;

                            this.x += d3.event.dx;
                            this.y += d3.event.dy;
                            d3.select(this).attr("transform", "translate(" + this.x + "," + this.y + ")");

                        })
                        .on("end", function () {});

d3.select("#svg-group-id").call(dragcontainer);


Is there a better (simpler) way to achieve this than manually updating the translate destination?

Solution

Yes, there is a simpler way to achieve this: just use d3.event.x and d3.event.y, holding their values in the bound data.

Thus, your drag function can be reduced to only this:

var dragcontainer = d3.drag()
    .on("drag", function(d, i) {
        d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + ","
        + (d.y = d3.event.y) + ")");
    })


And, since you don't use them, just drop your "start" and "end" listeners.

Here is the demo (click and drag the group around):



var dragcontainer = d3.drag()
.on("drag", function(d, i) {
d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + "," + (d.y = d3.event.y) + ")");
});
var g = d3.select("g").datum({x: 0, y: 0}).call(dragcontainer)








Code Snippets

var dragcontainer = d3.drag()
    .on("drag", function(d, i) {
        d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + ","
        + (d.y = d3.event.y) + ")");
    })

Context

StackExchange Code Review Q#142214, answer score: 2

Revisions (0)

No revisions yet.