onkami
onkami

Reputation: 9411

How to find a d3.js plot element by its connected data?

I have a d3.js plot that is made from an array of objects, such as:

svg.selectAll(".circ").data(dataArr) // dataArr is my array of objects
    .enter().append("circle")
    .attr("cy", function (d) {
        return d.y
    })
    .attr("cx", function (d) {
        return d.x
    })
    .attr("r", elemSize / 2)
    .on("dblclick", function (d, i) {
        itemWasClicked(d,i); // function to handle double click
    }

in the mentioned itemWasClicked(d,i) routine (where d is data of clicked element and i is index of it in array dataArr) I need to find the actual SVG element that was clicked and change its color.

How I could find a d3.js element by data attached to it? I do not want, unless necessary, to use attaching/searching by ID element. I only would do that if it is faster or there is no way to do otherwise.

Upvotes: 1

Views: 50

Answers (1)

Oleg
Oleg

Reputation: 9359

Inside of the event handler this is a direct reference to the actioned element.

See selection.on documentation:

The specified listener is invoked in the same manner as other operator functions, being passed the current datum d and index i, with the this context as the current DOM element.

So you can simply:

.on("dblclick", function (d, i) {
    changeColorOf(this);
}

Upvotes: 2

Related Questions