Accepted answer
for (var index in nodeValues) {
    var rect = svg.append("rect")
        .style("fill", "red" )
        .on('click', function(d,i) {
            // handle events here
            // d - datum
            // i - identifier or index
            // this - the `<rect>` that was clicked


I gave a vote to Stephen's answer but it's actually just missing one part - instead of .click, it's

.on("click", function(d){...

Here's some documentation. Also, I've jacked Mike's example of zooming with circles in order to implement the binder listener. Here's a fiddle that shows it.

Hope that helps!


I've refactored your code to be more D3-like -- in particular, you don't need a loop if you use D3's selections and data matching. The code then looks like this:

    .each(function(d) {
        var attrs = elementAttr(d);;
    .style("fill", rectColor);

Adding the click handler is just an additional statement at the end of this:

    .on("click", function() {"width", 120);

Complete demo here.

Related Query

More Query from same tag