Skip to content

Instantly share code, notes, and snippets.

@martinjc
Last active March 24, 2017 22:23
  • 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 martinjc/deaa106d7d313fa0140aecff7a0ce261 to your computer and use it in GitHub Desktop.
Using D3 to generate webpage content (Data: randomly generated)
license: mit
border: no

Simple example using D3 to generate content in a webpage

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3 example</title>
<script src="//d3js.org/d3.v4.min.js" charset="utf-8"></script>
</head>
<body>
<input type="button" onclick="update()" value="Update"/>
<div id="vis">
</div>
<script src="script.js">
</script>
</body>
</html>
function createRandomData() {
var numDataItems = Math.floor((Math.random() * 10) + 1);
var d = [];
for (var i = 0; i < numDataItems; i++) {
d.push(Math.floor((Math.random() * 50) + 1));
}
return d;
}
function update() {
var exampleData = createRandomData();
var visElement = d3.select('#vis');
var paras = visElement.selectAll('p')
.data(exampleData);
paras
.exit()
.remove();
var new_paras = paras
.enter()
.append('p');
new_paras.merge(paras)
.text(function(d, i) {
return "this is paragraph " + i + " and the data value is " + d;
});
}
update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment