

Let's first create a row and a column that our chart will be built in. Here's a super simple line chart made with D3. Using this in conjunction with clientWidth variable and the window.onresize event, it is very easy to create responsive d3 SVGs.
#D3 chart responsive resize code
To execute code when the user resizes or changes the orientation of their browser we need an event. It depends on the chart but something to consider could be an orientation change or a different layout at certain viewport break points, almost like CSS media queries. Responsive D3js Charts Viewport Resizing. Not all charts are going to look good, or more importantly visualize the data effectively at smaller sizes, simply shrinking it down isn’t always good enough. Changing it from 85 of window.innerWidth to 75 of window.innerWidth should only require a click and two keystrokes. Ctrl + F should only find a single match for width. attr('transform', 'translate(' + Math.min(width,height) / 2 + ',' + Math. In many existing examples of responsive D3 designand most of my previous projects the resize function restates lines of code. This will be looking at making the SVG grow/shrink in size depending on the SVG container. See the Pen Viewport Resize Debounce by Derek Morash ( on CodePen. var svg d3.select('.chart-container').append('svg'). This post will be a quick way to make any SVG or D3.js chart responsive. window.addEventListener('resize', function() ) To use an event listener you need three things the DOM element you want to target, the type of event you want to listen for (click, onmouseover, resize, etc), and a function for what you want to happen when that event is triggered.įor this example we want to listen to the “window” element for the “resize” event. Event listeners are used for every kind of user interaction, some commonly used events are mouse and keyboard inputs.

To execute code when the user resizes or changes the orientation of their browser we need an event listener. Data visualizations should respond to viewports exactly like every other element on the page, if not you could be failing a large number of your users.

There’s no point in making a responsive website if your chart is going to stick out the side of the viewport on a mobile device. Making responsive D3js charts is an essential part of creating data visualizations that are effective and accessible on the web.
