Skip to content

Instantly share code, notes, and snippets.

@eesur
Last active October 5, 2017 11:06
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 eesur/909c6a83a1d969918a5389966c5f431a to your computer and use it in GitHub Desktop.
Save eesur/909c6a83a1d969918a5389966c5f431a to your computer and use it in GitHub Desktop.
d3 | width of div container

simple example showing how to get the width of a div and use it's value/number

var containerWidth = +d3.select('.some-div').style('width').slice(0, -2)

it's an easy way to size/re-size drawings based on the containing div:

selection.append('svg')
    .attr('width', containerWidth)
    ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- http://www.basscss.com/ -->
<link href="https://unpkg.com/basscss@8.0.2/css/basscss.min.css" rel="stylesheet">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, Consolas, monaco, monospace;}
.blue { color: #1a068a; }
.yellow { color: #effe75; }
.blue-bg { background-color: #1a068a; }
.yellow-bg { background-color: #effe75; }
div {
min-height: 100vh;
}
.h0 {
font-size: 2.5rem;
line-height: 1;
}
@media screen and (min-width: 48em) {
.h0 { font-size: 5rem }
}
@media screen and (min-width: 80em) {
.h0 { font-size: 6vw }
}
</style>
</head>
<body>
<div class="clearfix">
<div class="col col-4 center blue-bg js-div-1">
<h1 class="h0 js-info-1 regular yellow"></h1>
</div>
<div class="col col-8 center yellow-bg js-div-2">
<h1 class="h0 js-info-2 regular blue"></h1>
</div>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<!-- d3 code -->
<script>
var d3 = window.d3
// show size values
function updateSize () {
d3.select('.js-info-1')
.text(getDivWidth('.js-div-1'))
d3.select('.js-info-2')
.text(getDivWidth('.js-div-2'))
}
// get the dom element width
function getDivWidth (div) {
var width = d3.select(div)
// get the width of div element
.style('width')
// take of 'px'
.slice(0, -2)
// return as an integer
return Math.round(Number(width))
}
window.onload = updateSize()
// update on window size change
window.addEventListener('resize', updateSize)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment