aitor aitor - 20 days ago 5
jQuery Question

D3.js chart responsive behavior

I'm trying to set listener to change a chart width with jQuery, when window width changes:

// Get width of parent div with jQuery

var widthContainer = $( ".chart" ).parent().width();

//set margins
// margin conventions https://bl.ocks.org/mbostock/3019563

var margin = {top: 0, right: 0, bottom: 30, left: 40};
var width = widthContainer - margin.left - margin.right;
var height = 211 - margin.top - margin.bottom;

// set chart dimensions

var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");


// listener

function changeWidth(){
widthContainer = $( ".chart" ).parent().width();
width = widthContainer - margin.left - margin.right;
}

$(window).resize(function(){
changeWidth();
console.log(widthContainer);
});


The
changeWidth()
function change the
widthContainer
variable, but chart dimensions does not change. Why?

Here is a working codepen (lines 13 to 40):
http://codepen.io/aitormendez/pen/LbRyWa?editors=0011

Thank you in advance

Answer

Your current changeWidth() only calculates the new width. you need to set the new width to the element you want. And you would also need to update your chart x-scale and redraw the charts.

Quick update to your codepen (i moved changeWidth and resize to the bottom plus adding redraw function).

var redraw = function(newWidth) {
  // update xscale
  escalax.range([0, newWidth]);
  d3.select('.xaxis').call(xAxis);
  deuda.selectAll("rect")
    .attr("width", function(d) {
      return rr(escalax(d[1]));
    });
  recono.selectAll("rect")
    .attr("x", function(d) {
      return rr(escalax(d[1]));
    })
    .attr("width", function(d) {
      return rr(escalax(d[2]));
    });
  provee.selectAll("rect")
    .attr("x", function(d) {
      return rr(escalax(d[1] + d[2]));
    })
    .attr("width", function(d) {
      return rr(escalax(d[3]));
    });
  credito.selectAll("rect")
    .attr("x", function(d) {
      return rr(escalax(d[1] + d[2] + d[3]));
    })
    .attr("width", function(d) {
      return rr(escalax(d[3]));
    });
}

function changeWidth() {
  widthContainer = $(".chart").parent().width();
  width = widthContainer - margin.left - margin.right;

  // update chart width
  d3.select('.chart')
    .attr('width', width);

  // redraw chart
  redraw(width);
}

$(window).resize(function() {
  changeWidth();
  console.log(widthContainer);
});

http://codepen.io/anon/pen/JbboQL?editors=1010