whileone
whileone

Reputation: 2805

create three circles using D3

I just started learning D3. From a tutorial website, I found the following code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
    </head>
    <body>
    <div id="viz"></div>
    <script type="text/javascript">

    var sampleSVG = d3.select("#viz")
    .append("svg")
    .attr("width", 100)
    .attr("height", 100);    

    sampleSVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50)
    .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
    .on("mouseout", function(){d3.select(this).style("fill", "white");});

    </script>
</body>
</html>

This code places a circle onto the screen. I want to know is there a way to place three circles on the screen individually? I am not talking about binding data to graphs and generating several circles at the same time like the following code does:

var dataset = [];
var i = 0;
for( i = 0; i < 5; ++i){
     dataset.push(Math.round(Math.random() * 100));         
}
i = 0.5;
var sampleSVG = d3.select("#viz")
    .append("svg")
    .attr("width", 500)
    .attr("height", 100);        

sampleSVG.selectAll("circle")
.data(dataset)
.enter().append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", function(){return (i++) * 80;})
.attr("cy", 40)
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "white");})
.on("mousedown", animateFirstStep); //animateFirstStep is some transition() function

Upvotes: 0

Views: 205

Answers (1)

Thanos
Thanos

Reputation: 3059

Create an array with your div IDs and loop through this.

var tempArray = ["viz", "viz1", "viz2", "viz3"];

Check this fiddle: http://jsfiddle.net/EhqVh/

JS

var tempArray = ["viz", "viz1", "viz2", "viz3"];
for (var i = 0; i < tempArray.length; i++) {
    var sampleSVG = d3.select("#"+tempArray)
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);

    sampleSVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50)
    .on("mouseover", function () {
    d3.select(this).style("fill", "aliceblue");
    })
        .on("mouseout", function () {
        d3.select(this).style("fill", "white");
    });
}

HTML

<div id="viz"></div>

Upvotes: 2

Related Questions