Skip to content

Instantly share code, notes, and snippets.

@rclark
Last active December 23, 2015 18:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rclark/6675543 to your computer and use it in GitHub Desktop.
// [Official documentation](https://github.com/mbostock/d3/wiki/Selections)
// Some "data". These might be "models" in your app.
// D3 always wants an array of data, since no one likes
// to say "datum".
var data = [
{
id: "first",
name: "This is the First",
description: "This is a description of the first.",
bgColor: "#dec8da"
},
{
id: "second",
name: "This is the Second",
description: "This is a description of the second.",
bgColor: "#c6e3f8"
},
{
id: "third",
name: "This is the Third",
description: "This is a description of the third.",
bgColor: "#c7e6c7"
},
];
// Use D3 as your "views" layer. Chaining is rampant here.
d3.select('#container') // Selects the `#container` element.
.selectAll('div') // "Selects" non-existent `div` children of the container.
// This doesn't make a lot of sense until you start being dynamic.
.data(data) // Binds the array of data objects to my selection.
.enter() // `.enter()` refers to "new data" that is adding to my container.
// Also doesn't make a lot of sense until you start being dynamic.
.append('div') // Creates a `div` for each element in my data array. Now we're dealing
// with a set of selected `div` elements.
// Now can start building the DOM details.
// You could pass in static strings, or write functions like these where `d` refers to
// the single datum bound to any particular element. That is, one entry from the array
// above for each `div`.
.attr('id', function (d) { return d.id; })
.classed('one-model', true)
.text(function (d) { return d.name; })
.style('background-color', function (d) { return d.bgColor; })
// The functions are also passed in the datum's index in the array
.style('border-bottom', function (d, i) {
if (i !== data.length - 1) {
return 'none';
}
})
// You can also respond to events, with access to the relevent datum.
.on('click', function (d) { alert(d.description); });
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>D3 Selectors</title>
<style type="text/css">
.one-model {
height: 100px;
line-height: 100px;
border: 1px solid #5b5bba;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="demo.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment