D3’s .drag Method

      This will be a very short post, the main purpose is to demonstrate a simple working example of a .drag function. When trying to implement this function I found the information on D3’s api to be overly complicated and lacking examples so I decided to do a small search for it online. I came across several different comments on how to implement the .drag method which were either on StackOverflow where they were contradicting each other and more concerned with why the other members method wouldn’t work as opposed to putting out a working code snipped, or blog posts which contained extremely complicated examples which couldn’t be copied and pasted into your code. This implementation has all of the D3 code you would need in order to implement the .drag method.

var mouse = {x: 500, y: 500};

var svg = d3.select("body").append("svg").attr("width", 1200).attr("height", 550);

var drag = d3.behavior.drag()
  .on("drag", function () {
    var loc = d3.mouse(this);
    mouse = {x: loc[0], y: loc[1]};
    d3.select(this).attr('cx', mouse.x).attr('cy', mouse.y);
  });

var hero = svg.selectAll("circle.hero").data([1]).enter().append("circle").attr('class','hero').attr("cx", 1100)
  .attr("cy", 450)
  .attr("r", 20)
  .style('fill', 'red').call(drag);

      The line creating the svg element is there in order to create the box in which the dragable element will be present. If you are using simple css to do so and you already have a box element to contain your draggable element this line would not be necessary.

      Notice that I first created and assigned D3’s .drag method to a variable called “drag” and then called it on circle with the .hero class as it was created.

Paulo Diniz