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.
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
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With