Skip to content

Instantly share code, notes, and snippets.

@emeeks
Last active August 29, 2015 14:09
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 emeeks/30377d4a70ffaef89faf to your computer and use it in GitHub Desktop.
Save emeeks/30377d4a70ffaef89faf to your computer and use it in GitHub Desktop.
Ch. 1, Fig. 25 - D3.js in Action

This is the code for Chapter 1, Figure 25 from D3.js in Action showing simple data binding using an array of filler data (literally an array of four instances of the word "filler"). This highlights three key aspects of data binding:

  • The number of elements created by the .enter() behavior is the length of the data array referenced in .data() minus the number of elements bound to the selection. In other words, because the selection in this example already has one div element created (the div onscreen with a gray border) then only three new elements are created by .enter() despite there being four datapoints in the array.
  • Multiple elements can be created for each enter event. Here, a div and a child span are created for each datapoint.
  • Only the number of elements created is tied to number of array values--the content of the elements does not need to be based on the content of the data. Here, the new div and span elements are filled with text that has nothing to do with the data array.
<html>
<head>
<title>D3 in Action Chapter 1 - Example 2</title>
<meta charset="utf-8" />
<script src="http://d3js.org/d3.v3.min.js" type="text/JavaScript"></script>
</head>
<style>
#vizcontainer {
width: 200px;
height: 100px;
border: 1px gray solid;
}
</style>
<body>
<div id="vizcontainer">
</div>
</body>
<footer>
<script>
var someData = ["filler", "filler", "filler", "filler"];
d3.select("body")
.selectAll("div")
.data(someData)
.enter()
.append("div")
.html("Wow")
.append("span")
.html("Even More Wow")
.style("font-weight", "900");
</script>
</footer>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment