score:1

Accepted answer

You handler should access the target node using

d3.select(this)

instead of circle.

<!DOCTYPE html>
    <html>
      <head>
        <!-- Load D3 from site -->
        <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

    <!-- End CSS (Styling) -->
    </head>
      <body>

    <h3></h3>

  <!-- Begin D3 Javascript -->
  <script type="text/javascript">

    var boxWidth = 600;  
    var boxHeight = 400;

    var box = d3.select('body')  
            .append('svg')
            .attr('class', 'box')
            .attr('width', boxWidth)
            .attr('height', boxHeight);

    var drag = d3.behavior.drag()  
             .on('dragstart', function(c) { d3.select(this).style('fill', 'red'); })
             .on('drag', function(c) { d3.select(this).attr('cx', d3.event.x)
                                            .attr('cy', d3.event.y); })
             .on('dragend', function(c) { d3.select(this).style('fill', 'black'); });


     var circle = box.selectAll('.draggableCircle')  
                .data([{ x: (boxWidth / 3), y: (boxHeight / 3), r: 25 },{ x: (boxWidth / 2), y: (boxHeight / 2), r: 25 }])
                .enter()
                .append('circle')
                .attr('class', 'draggableCircle')
                .attr('cx', function(d) { return d.x; })
                .attr('cy', function(d) { return d.y; })
                .attr('r', function(d) { return d.r; })
                .call(drag)
                .style('fill', 'black');

  </script>
  </body>
</html>


Related Query

More Query from same tag