1

This has been asked a lot of times, yet this answer does not appear to be working for me. I have the following fiddle, for which I've added the resize function as below:

 // RESIZE
      var aspect = width / height,
        chart = d3.select('svg');
      d3.select(window)
        .on("resize", function() {
          var targetWidth = chart.node().getBoundingClientRect().width;
          chart.attr("width", targetWidth);
          chart.attr("height", targetWidth / aspect);
        });

When it loads it doesn't fill up the window 100%, nor does it change when the window resizes. What am I doing wrong?

user72840184
  • 49
  • 3
  • 13

1 Answers1

1

There are some problems with your solution when compared with the solution in the answer you linked. You are getting the new size from the svg:

var targetWidth = chart.node().getBoundingClientRect().width;

which has the same size as before the resize event. Instead, in the linked answer the svg element is inside a div, and the targetWidth is taken from the div. Additionally, I think that approach is not valid for more complex svgs (right now I don't know the reasons, TBH).

However, another option could be redraw the chart (see fiddle) on resize event:

  // RESIZE
  var aspect = width / height,
    chart = d3.select('svg');
  var container = d3.select('#container');;
  d3.select(window)
    .on("resize", function() {
      var targetWidth = container.node().getBoundingClientRect().width;
      var targetHeight = targetWidth / aspect;

                d3.select('svg').remove();

      var svg = d3.select("#container").append("svg")
        .attr("width", targetWidth + margin.left + margin.right)
        .attr("height", targetHeight + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      draw(svg, targetWidth, targetHeight);       
    });

This solution requires encapsulating in a function the code that draws the chart. Probably it's not very suitable in terms of computational resources, but maybe works for your purposes.

Pablo EM
  • 6,190
  • 3
  • 29
  • 37