Nikunj Aggarwal Nikunj Aggarwal - 7 days ago 5
Javascript Question

duplicating the whole svg element using d3.js

I am creating a

rectangle
using
d3.js
, inside that rectangle i am creating 10 smaller rectangles`.

i want to replicate whole thing into another svg element on mouse click.

jsfiddle
link of the code : http://jsfiddle.net/nikunj2512/XK585/

Here is the code:

var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);

//Draw the Rectangle
var rectangle = svgContainer.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("fill", "red")
.attr("width", 200)
.attr("height", 200);

var bigRectContainer = d3.select('#bigRectContainer').append('svg')
.attr('width', 200)
.attr('height', 200);
var dim = 20;
var x = 0;
var y = 0;
for (i = 1; i < 11; i++) {

x = 10 + (i-1)*dim;
//alert(x);
y = 10;

svgContainer.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 20)
.attr("height", 20)
.style("fill", "black");
}

var bigRectContainer = svgContainer.append("g");
svgContainer.selectAll("rect").on("click", function () {
var littleRect = d3.select(this);
console.log(littleRect)

var bigRect = bigRectContainer.selectAll("rect")
.data(littleRect)
.enter()
.append("rect");

});


Please tell me where i made the mistake...

Answer

I'm not entirely certain what you're trying to do with the code you've posted, but I thought that duplicating an entire SVG node was interesting. It turns out it's quite easy to do with selection#html - this doesn't work on the SVG node, but it does work on its container, so it's easy to clone the whole node:

function addAnother() {
    var content = d3.select(this.parentNode).html();
    var div = d3.select('body').append('div')
        .html(content);
    div.selectAll('svg').on('click', addAnother);
}

svg.on('click', addAnother);

See working fiddle here. Note that this only works if the SVG node is the only child of its parent - otherwise, you might need to wrap it somehow.

Comments