Skip to content

Instantly share code, notes, and snippets.

Last active February 20, 2019 14:41
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Responding to Resize
license: mit

Check out my video course: D3.js in Motion. Learn D3 fast!

This example shows how to make a D3 visualization that fills up the size of the page at the time it is loaded AND whenever the page is resized by the user. This is necessary when, for example, you want to be able to load your visualization "full screen" and give users the ability to size the window however they want to. This example was created to address this question on the D3 Google Group: Any advice for setting width in iframes with D3?.

To experience the resize behavior, run this example full-screen and resize the browser.

<!DOCTYPE html>
<meta charset="utf-8">
<title>Dynamic Size Example</title>
<script src=""></script>
/* Make the chart container fill the page using CSS. */
#chart {
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
<div id="chart"></div>
var chartDiv = document.getElementById("chart");
var svg ="svg");
function redraw(){
// Extract the width and height that was computed by CSS.
var width = chartDiv.clientWidth;
var height = chartDiv.clientHeight;
// Use the extracted size to set the size of an SVG element.
.attr("width", width)
.attr("height", height);
// Draw an X to show that the size is correct.
var lines = svg.selectAll("line").data([
{x1: 0, y1: 0, x2: width, y2: height},
{x1: 0, y1: height, x2: width, y2: 0}
.style("stroke-width", 50)
.style("stroke-opacity", 0.4)
.style("stroke", "black")
.attr("x1", function (d) { return d.x1; })
.attr("y1", function (d) { return d.y1; })
.attr("x2", function (d) { return d.x2; })
.attr("y2", function (d) { return d.y2; })
// Draw for the first time to initialize.
// Redraw based on the new size whenever the browser window is resized.
window.addEventListener("resize", redraw);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment