user5011081
user5011081

Reputation:

D3 - Finding an SVG Element with the same data

In the attached fiddle, you will find a variable dataset that is a JSON object with a nested array that contains three different JSON objects. The code below appends two circle elements (of different colours and heights) to the canvas for each of these objects. The x position is based on a field in the JSON and upon clicking on the circle, prints another field in the console (you'll notice this JSON data is of Tweets pulled from the Twitter API).

What I want is for when a circle is clicked, a line is appended from that circle to the circle of the other colour which has the same data object tied to it. You will see in the data.ForEach function that there is an ID set for each object:

d.Id = IDLoop;
IDLoop ++;

So say if I click on the green circle with the bound data of ID 2, a line should be made from that green circle to the red circle with data ID 2. This I presume will be require adjust the click behaviour on the circles which I have started below based on what I think it will look like:

.on('click', function (d) {
        console.log(d.Tweet);
        // add code from here...
        canvas.append("line")
          .attr("x1", d3.select(this).attr("cx"))
          .attr("y1", d3.select(this).attr("cy"))
          .attr("x2", 
              function(d) {
               // Something here I believe that references d.Id?   
              })
          .attr("y2",
              function(d) {
               // Something here I believe that references d.Id?
              })
          .attr("stroke", "#42f4ee")
          .attr("stroke-width", 2)
});

Many thanks in advance for any help you can offer!

Upvotes: 1

Views: 182

Answers (1)

JusMalcolm
JusMalcolm

Reputation: 1431

You can use d3 Selection's .filter() option to select the second element based on it's bound data.

So if you bind a click listener to the first element, you can select all circle elements and filter on the data attribute 'ID'. In your case, you'll probably want to add a separate class or data attribute to distinguish the second group of circles from the first.

eg:

`var selected = canvas.selectAll("circle").filter(function(e) {
    return e.Username === d.Username;
})`

edited to include content from Gerardo's fiddle

Upvotes: 1

Related Questions