Created
July 20, 2015 16:40
-
-
Save johndhancock/a76e7a1d8b18972a5d4e to your computer and use it in GitHub Desktop.
Starter js for responsive d3 charts. Assumes jquery and a div for your d3 chart with id of "chart". Your d3 charts will redraw to the new #chart with upon window resize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is a starter template for a responsive d3 chart | |
// it assumes you're using jquery, and that the div your chart | |
// will live in has an id of "chart" | |
$(document).ready(function() { | |
var windowWidth = $(window).width(); | |
//variable setup: chartcontainer and it's width | |
var chartBox = $('#chart'); | |
var boxWidth = chartBox.width(); | |
function drawChart() { | |
// removing our old, now incorrectly sized svg | |
chartBox.html(''); | |
// chart dimension setup. You will want to adjust the chart's height and margins depending on your chart | |
var margin = {top: 20, right: 10, bottom: 20, left: 10}, | |
w = boxWidth - margin.left - margin.right, | |
h = 300 - margin.top - margin.bottom; | |
//sample svg added for demonstration purposes. | |
//feel free to use or discard | |
var svg = d3.select('#chart') | |
.append('svg') | |
.attr('width', w) | |
.attr('height', h) | |
.style('background-color', 'grey'); | |
} | |
drawChart(); | |
$(window).resize(function() { | |
setTimeout(function() { | |
// getting the new width of the window | |
var newWindowWidth = $(window).width(); | |
//we check to make sure the new width is not equal to the old width | |
//we do this because some versions of chrome on mobile count a scroll event as a window resize event | |
//we only want to redraw the chart if the width of the window changes | |
if (newWindowWidth !== windowWidth) { | |
//set our windowWidth to the new width | |
windowWidth = newWindowWidth; | |
//reset our boxWidth variable | |
boxWidth = chartBox.width(); | |
//redraw our chart | |
drawChart(); | |
} | |
}, 250) | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment