Study of Drag Behavior - variation 2

by Nivaldo

HTML

<!--
- references:
    - http://bl.ocks.org/mbostock/6123708
- huge lesson: because the dragging is being called from the g, the transform needs to take into account the displacement of the circle from the origin of g (20,20; this is cx, cy); only if you do that the pointer will be in the right location ***AND*** the styling of the cursor will show...need a deeper understanding of that)
    - if the drag is called from the circle, then the code inside dragged will be something like: d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y); also, the styling to red would work as well, but it will not drag the text...would have to be done separately
- if the circle is styled, it will have precedence of the styling of the g; the only way to paint the circle red is to not style it with anything (it will be black); this is why it works for the text, it is not styled
-->

CSS

.group circle {
    fill: blue;
}

circle.dragging, text.dragging {
    cursor: move;
    fill: red;
}

JavaScript

var drag = d3.behavior.drag()
    .on("dragstart",dragstarted)
    .on("drag",dragged)
    .on("dragend",dragended);

var svg = d3.select("body")
  .append("svg");

var g = svg
  .append("g")
    .attr("class","group")
    //.call(drag)
;

var circle = g
  .append("circle")
    .attr("cx",20)
    .attr("cy", 20)
    .attr("r",10)
    .call(drag);

var circle = g
  .append("circle")
    .attr("cx",40)
    .attr("cy", 40)
    .attr("r",10)
    .call(drag);

var text = g
  .append("text")
    .attr("x",30)
    .attr("y",20)
    .text("circle")
    .call(drag);
          
function dragged() {
    console.log(this);
    if (d3.select(this).attr("cx")) {
        console.log("is circle");
        d3.select(this)
            .attr("cx", d3.event.x)
            .attr("cy",d3.event.y);
    };
    
    if (d3.select(this).attr("x")) {
        console.log("is text");
        d3.select(this)
            .attr("x", d3.event.x)
            .attr("y",d3.event.y);
    };
};

function dragstarted() {
    d3.event.sourceEvent.stopPropagation();
    d3.select(this)
        .classed("dragging",true);
};

function dragended() {
    d3.select(this)
        .classed("dragging",false);
};