Adding div to circle in d3.js

I have a d3.js donut bar and I want to put some information into it. I can add a text element, but I want to place formatted information there, so I decided to add a div to mouseover:

$(".arc").on("mouseover",(function(){
d3.select("text").remove();
var appendingString="<tspan>"+cityName[$(this).attr("id")]+"</tspan> <tspan>"+$(this).attr("id")+"%</tspan>";
group
.append("text")
.attr("x",-30)
.attr("y",-10)
.text(appendingString);
})); 

For some reason, the div is added successfully with the information I need, but not displayed. What is the correct way to add it or are there alternative ways? Full script if necessary:

<script>
var cityNames=["","","",""];
var cityPercentage=[50,30,20,10];
var width=300,
    height=300,
    radius=100;
var color=d3.scale.linear()
            .domain([0,60])
            .range(["red","blue"]);
var cityDivision = d3.select("#cities")
            .append("svg")
            .attr("width", width)
            .attr("height", height)
            .attr("class","span4");
var group=cityDivision.append("g")
.attr("transform","translate(" + width / 2 + "," + height / 2 + ")");
var arc=d3.svg.arc()
    .innerRadius(radius-19)
    .outerRadius(radius);
var pie= d3.layout.pie()
    .value(function(d){return d;});
var cityName={
    50:"",
    30:"",
    20:"",
    10:""
}
var arcs=group.selectAll(".arc")
    .data(pie(cityPercentage))
    .enter()
    .append("g")
    .attr("class","arc")
    .attr("id",function(d){return d.data;});
    arcs.append("path")
    .attr("d",arc)
    .attr("fill",function(d){return color(d.data);});
//   
    group
    .append("circle")
    .style("fill","white")
    .attr("r",radius-20);
$(".arc").on("mouseover",(function(){
    d3.select("div.label").remove();
    var appendingString=cityName[$(this).attr("id")]+"\n "+$(this).attr("id")+"%";
    group
    .append("div")
    .attr("class","label")
    .html(appendingString);
}));
</script>
+4
source share
1 answer

You cannot enter divdirectly into an element svg. You have two options:


tspan :

$(".arc").on("mouseover",(function(){
    d3.select("text").remove();
    var text = group
    .append("text")
    .attr("x",-30)
    .attr("y",-10)
    .selectAll('tspan')
    .data([cityName[$(this).attr('id')], $(this).attr('id') + '%'])
    .enter()
    .append('tspan')
      .attr('x', 0)
      .attr('dx', '-1em')
      .attr('dy', function (d, i) { return (2 * i - 1) + 'em'; })
      .text(String);

})); 

Sidenote: , ([0-9]*) id. id , .

+6

Source: https://habr.com/ru/post/1536230/


All Articles