Search code examples
javascriptjqueryd3.jsrect

programmatically access a d3 rectangle on click event


I create a few d3 rectangles and give them each a click event: First I created the container:

var svgContainer = d3.select("#Container")
                                .append("svg")
                                .attr("width", 720)
                                .attr("height", 45);

then in a for-loop I create each rectangle inside the container:

var rectangle = svgContainer.append("rect")  
                                        .attr("x", 10 + xAppend)
                                        .attr("y", 5)
                                        .attr("width", 120)
                                        .attr("height", 35)
                                        .attr("stroke", "black")
                                        .attr("name", name)
                                        .on("click", function () {
                                            // Click event...
                                            //...
                                        });

Now in a different function, I want to trigger that on-click function. The variable 'rectangle' is not global, it gets created inside the for loop and I create 6 rectangles from the for loop.

What I have done so far inside the other function is:

var tempContainer = d3.select("#Container");
var test = tempContainer.selectAll("rect");   

This gives me a array of 1 object and that object is an array of the 6 rectangles, then I loop through the array to find the rectangle I want.

for (var i = 0; i < test[0].length; i++) {
    if (search.item.desc == test[0][i].attributes[5].value)
    {
        var testing = test[0][i];
        //testing.attributes[5].value   works fine
        //testing.click();       does not work
        //testing.on('click')();        does not work
    }
}

Inside the for-loop the variable 'testing' is the rectangle I want, I can access its attributes like I did in the if statement above. But I cannot access and trigger the on click function.


Solution

  • The on-click event function can be accessed by using the following:

    testing.__onclick();