Andrej
Andrej

Reputation: 3839

Responsive SVG with d3.js and height attribute

I have two div elements side by side. In the first div (called #scatterplot) there is a plot rendered automatically. SVG container size is set automatically using the following code in d3.js:

var vis = d3.select("#scatterplot")
   //container class to make it responsive
   .classed("svg-container", true)
   .append("svg")
   //responsive SVG needs these 2 attributes and no width and height attr
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 700 700")
   //class to make it responsive
   .classed("svg-content-responsive", true)
   .append("g")
   .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

The corresponding CSS code is as follows:

.svg-container {
    display: inline-block;
    position: relative;
    width: 100%;
    padding-bottom: 100%; /* aspect ratio */
    vertical-align: top;
    overflow: hidden;
}
.svg-content-responsive {
    display: inline-block;
    position: absolute;
    top: 10px;
    left: 0;
}

Question: The second div is called #wordcloud. I need to adjust the height of the #wordcloud according to #scatterplot div. Any suggestion how to accomplish this?

Upvotes: 0

Views: 403

Answers (1)

Alexander
Alexander

Reputation: 4527

You could use d3.style() method to set #wordcloud height within inline style. For example:

var height = d3.select('#scatterplot').node().getBoundingClientRect().height;
d3.select('#wordcloud').style('height', height + 'px');
div {
  width: 50%;
  float: left;
}

#scatterplot {
  background: #f00;
}

#wordcloud {
  background: #0f0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="scatterplot">
  <p>The text is used<br/>to change height<br/>of red div.</p>
</div>
<div id="wordcloud">
  <p>The heights of red and green divs are same.</p>
</div>

Upvotes: 1

Related Questions