Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign click event to every svg element in d3js

I have added nine rectangles in a svg element. How do i add click event to each one?

var nodeValues = [0, 1, 2, 3, 4, 5, 6, 7, 8];

var colors = ["aqua", "darkblue", "black", "red", "green", "gray", "navy", "orange", "teal"];

var main = d3.select("#main");

var svg = main.append("svg")
    .data(nodeValues)
    .attr("width", 300)
    .attr("height", 300);

var elementAttr = function (index) {
    return {
        x: (index % 3) * 100,
        y: Math.floor((index / 3)) * 100,
        width: 95,
        height: 95
    }
}

for (var index in nodeValues) {
    var rect = svg.append("rect")
        .attr(elementAttr(index))
        .style("fill", "red" );
}

Here is the Jsfiddle.

UPDATE : I wish to change attributes like width of rectangle on a click event.

like image 352
vjdhama Avatar asked Nov 30 '25 03:11

vjdhama


2 Answers

for (var index in nodeValues) {
    var rect = svg.append("rect")
        .attr(elementAttr(index))
        .style("fill", "red" )
        .on('click', function(d,i) {
            // handle events here
            // d - datum
            // i - identifier or index
            // this - the `<rect>` that was clicked
        });
}
like image 107
Stephen Thomas Avatar answered Dec 02 '25 16:12

Stephen Thomas


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:

svg.selectAll("rect")
    .data(nodeValues).enter().append("rect")
    .each(function(d) {
        var attrs = elementAttr(d);
        d3.select(this).attr(attrs);
    })
    .style("fill", rectColor);

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

    .on("click", function() {
        d3.select(this).attr("width", 120);
    });

Complete demo here.

like image 30
Lars Kotthoff Avatar answered Dec 02 '25 17:12

Lars Kotthoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!