3

Trying to drag groups. Why doesn't origin work here? Notice how it jumps when you first click on it? JSFIDDLE Based on this: http://bl.ocks.org/mbostock/1557377

var drag = d3.behavior.drag() // construct drag behavior
.origin(function() { 
    var t = d3.select(this);
    return {x: t.attr("x"), y: t.attr("y")};
})
.on("drag", function(d,i) {
    d.x += d3.event.dx
    d.y += d3.event.dy
    d3.select(this).attr("transform", function(d,i){
        return "translate(" + [ d.x,d.y ] + ")"
    })
});
  • You're mixing setting positions through `cx` and `cy` and `transform` here. It's much easier if you use just one and set the drag only on the circles: https://jsfiddle.net/pob7xhuo/2/ – Lars Kotthoff Jul 13 '15 at 19:57
  • What I'm after is to be able to click on the circle or the text and be able to drag both of them as a unit without it jumping to a new position the first time I click. Unfortunately the one you sent doesn't drag the text along with it. (I couldn't get the fiddle to work, but locally it just moves the circle only). Here's a good example of what I'm after, but had trouble getting it to work locally http://bl.ocks.org/enjalot/raw/1378144/ . It's not using origin at all, but it works? –  Jul 13 '15 at 20:21
  • 1
    Then set the `transform` on the `g` elements and not the `circle`s: https://jsfiddle.net/pob7xhuo/3/ – Lars Kotthoff Jul 13 '15 at 20:36
  • Ah, of course. Thanks Lars. I can write answer if you like? –  Jul 13 '15 at 20:42
  • Just posted an answer now :) – Lars Kotthoff Jul 13 '15 at 21:31

1 Answers1

1

You're mixing different ways of setting positions -- you're setting transform and cx and cyon the circles, but not on thegelements that you want to drag. While it can be made to work by computing the various offsets, it's much easier if you set the position for the things you're interested in (i.e. theg` elements) and that the drag behaviour is called on.

var svgG = svg.append("g")
  .attr("transform", function(d) { return "translate(" + [ d.x,d.y ] + ")"; })
  .call(drag);

Complete example here.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Thanks again. For some reason your fiddles don't work for me. But if I make one myself using your code, it does. Anyway, [here's mine](http://jsfiddle.net/airwwwave/k74rs1fk/1/) –  Jul 13 '15 at 21:36
  • Hmm, interesting. Maybe some browser security restrictions? It's loading the D3 library through an unsecured connection and some browsers block this automatically. – Lars Kotthoff Jul 13 '15 at 23:57
  • Yes, I think you're right. I asked and got some [feedback here](http://stackoverflow.com/questions/31394233/jsfiddle-d3-is-not-defined-differences). –  Jul 14 '15 at 15:08