Search code examples
javascriptd3.jssvghref

How would I apply an href to the ENTIRE svg?


I've got a page where I build a bunch of pie charts. On each one, I want to add an href to another location on the page.

Currently my code works, but it only applies the href to the individual pieces of the pie chart, as well as the text. So for example, if you click on a ring of the pie chart, it will work like it should, but if you click on the space between the rings, it will not.

The SVG itself is much larger and easier to click, but even though I append the anchor tag to the svg, it only applies to the elements within the SVG. How do I correct this behavior?

function pieChartBuilder(teamName, values) {
    var dataset = values;

    var trimTitle = teamName.replace(' ', '');
    trimTitle = trimTitle.toLowerCase();

    var width = 175,
        height = 175,
        cwidth = 8;

    var color = d3.scale.category20();

    var pie = d3.layout.pie()
        .sort(null);

    var arc = d3.svg.arc();

    var svg = d3.select("#pieChart").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("a") // here is where I append the anchor tag to the SVG, but it only applies to the individual elements within.
        .attr("href", ("#" + trimTitle))
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

    var gs = svg.selectAll("g").data(d3.values(dataset)).enter().append("g");
    var path = gs.selectAll("path")
        .data(function (d) { return pie(d); })
        .enter().append("path")
        .attr("fill", function (d, i) { return color(i); })
        .attr("d", function (d, i, j) { return arc.innerRadius(5 + cwidth * j).outerRadius(3 + cwidth * (j + 1))(d); });

    svg.append("text")
        .attr("class", "title")
        .attr("x", 0)
        .attr("y", (0 - (height / 2.5)))
        .attr("text-anchor", "middle")
        .style("fill", "#808080")
        .text(teamName);

}

Solution

  • I think you just have the selectors the wrong way round. You want to have the svg inside an a tag right?:

    d3.select("#pieChart")
      .append("a")
      .append("svg");
    

    You (1) select the pieChart, then (2) append an a tag to it, then you (3) append the svg to that.