0

I have an array ["a", "b", "c", "d"] from which I build two svg objects on the page. In first there is a chart and in second svg there are controls for this chart. Both have elements bound to the same data from the array. I want to use controls area as buttons to make chart elements active according to a clicked button from controls area.

If I click a button, I receive index in its click event and want to make a chart element active by highlighting it with a color. First I make chart elements then buttons area, both in the same way, like this:

    elements = d3.select('g.elements')

So, I have elements object for the chart, and an index from the click event, which I hope I can use to get respective item from this object in d3 way.

Please advise how I can get an object from elements with a specific index properly so that I can handle it with d3 methods and properties, not just as a DOM element?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • In all handlers, you're passed the datum and the index, e.g. `.on("click", function(d, i) { // d is datum, i index, this DOM element });` – Lars Kotthoff Feb 24 '14 at 20:40
  • I need to modify not `this` but an element in another chart but linked to the same data as the clicked element. Right now I use `elements.select(":nth-child(#{i + 1})").attr("opacity", 1)` (coffeescript) but it doesn't look nor proper neither elegant to me. – Sergei Basharov Feb 24 '14 at 20:46
  • Then you need to set an appropriate ID or class that allows you to select the element given the data. – Lars Kotthoff Feb 24 '14 at 20:47
  • Example / more explanation of what @LarsKotthoff is suggesting: http://stackoverflow.com/a/21470867/3128209 I don't see anything wrong with using `nth-child`, so long as you're careful to keep all the relevant elements in their own group and in the correct order. – AmeliaBR Feb 24 '14 at 22:49

1 Answers1

1

Not entirely clear. Do you want to do this:

d3.select("elements").each(function(d,i) {
    if(i == myIndex) {
        //do stuff
    }
})

This can be done using filter / select as well.

My view is that the d3.js way is to annotate the original data and draw the entire view again. So if your data was [{id:"a"}, {id:"b"},...] then when "a" was pressed you might update the object to: {id:"a", pressed:true}, and then redraw your two svg objects based on the new data (making "a" active based on the presence of "pressed" being true.

Glenn
  • 5,334
  • 4
  • 28
  • 31