Skip to content

Instantly share code, notes, and snippets.

@jqtrde
Forked from drewbo/resize.md
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqtrde/dc541bc5f03f48dcf8b1 to your computer and use it in GitHub Desktop.
Save jqtrde/dc541bc5f03f48dcf8b1 to your computer and use it in GitHub Desktop.

How to create D3 visualizations that resize and scale well

When creating the SVG, add this bit of D3:

.attr("id","chart")
.attr("viewBox","0 0 960 500")
.attr("perserveAspectRatio","xMinYMid")

Then later in the code, add this bit of jQuery:

var chart = $("#chart"),
    aspect = chart.width() / chart.height(),
    container = chart.parent();
$(window).on("resize", function() {
    var targetWidth = container.width();
    chart.attr("width", targetWidth);
    chart.attr("height", Math.round(targetWidth / aspect));
}).trigger("resize");

The end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment