1

JS and drawing circles, I am dragging it to certain coordinates, now I need to retrieve x-cordinate, y-coordinate and colour(which I am assigning randomly) of selected Item, I am able to get x-cord, y-cord, radius but colour is showing null. Here I am assigning colour and coordinate:

svg.selectAll("circle")
   .data(circles)
   .enter().append("circle")
   .attr("cx", function (d) {
       return d.x;
   })
   .attr("cy", function (d) {
       return d.y;
   })
   .attr("r", radius)
   .style("fill", function (d, i) {
       return color(i);
   })
   .call(d3.drag()
   .on("start", dragstarted)
   .on("drag", dragged)
   .on("end", dragended));

here I am trying to retrieve coordinate and colour of selected item

   function dragended(d) {
      d3.select(this).classed("active", false);

      console.log('dragged  ' + flagForCircle + ' xCord ' + d3.select(this).attr('cx')+' ycord ' + d3.select(this).attr('cy') +' color ' + d3.select(this).attr('fill'));

      d3.select(this).on('mousedown.drag', null);


      }


   }
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171

2 Answers2

4

You're setting the fill with style:

.style("fill", function (d, i) {
    return color(i);
})

Therefore, you have to use style in the getter:

d3.select(this).style('fill')
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • It's worth keeping in mind, though, that this is not necessarily true the other way around: https://stackoverflow.com/a/45033107/4235784 — https://jsfiddle.net/nvs2u1Lj/ – altocumulus Sep 19 '17 at 09:04
0

Note for anyone reading this. I'm using d3 version 5.7. In my circumstance I needed to keep the fill constant if certain criteria were met, to do so I implemented the following.

.style("fill", function (d, index, element) {
  if(criteria) {
     return element[index].style.fill; // Get fill of current item
  } else {
    return "black"
  }
})
John Duskin
  • 355
  • 5
  • 12