D3 json with ajax (CORS enabled)
Access-Control-Allow-Origin: *
by Simon Raper
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<form>
<label>
<input type="radio" name="mode" value="size" checked="true" />Size</label>
<label>
<input type="radio" name="mode" value="count" />Count</label>
</form>
<button id="loadData">Load data</button>
CSS
body {
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
form {
position: absolute;
right: 10px;
top: 10px;
}
.node {
border: solid 1px white;
font: 10px sans-serif;
line-height: 12px;
overflow: hidden;
position: absolute;
text-indent: 2px;
}
JavaScript
var margin = {
top: 40,
right: 10,
bottom: 10,
left: 10
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var color = d3.scale.category20c();
var treemap = d3.layout.treemap()
.size([width, height])
.sticky(true)
.value(function (d) {
return d.size;
});
var div = d3.select("body").append("div")
.style("position", "relative")
.style("width", (width + margin.left + margin.right) + "px")
.style("height", (height + margin.top + margin.bottom) + "px")
.style("left", margin.left + "px")
.style("top", margin.top + "px");
var url = "https://afternoon-anchorage-24816.herokuapp.com/api/data?audience=younger_segment";
var dispatcher = d3.dispatch('jsonLoad');
d3.select('#loadData').on('click', function() {
d3.json(url, callback);
});
// optional dispatcher
dispatcher.on('jsonLoad', function(data) {
// triggered afer json is loaded (just if you want to do additional stuff here.)
console.log(data);
});
var callback = function (error, root) {
dispatcher.jsonLoad(root); // can trigger an event that new data are here
var node = div.datum(root).selectAll(".node")
.data(treemap.nodes)
.enter().append("div")
.attr("class", "node")
.call(position)
.style("background", function (d) {
return d.children ? color(d.name) : null;
})
.text(function (d) {
return d.children ? null : d.name;
});
d3.selectAll("input").on("change", function change() {
var value = this.value === "count" ? function () {
return 1;
} : function (d) {
return d.size;
};
node.data(treemap.value(value).nodes)
.transition()
.duration(1500)
.call(position);
});
};
function position() {
this.style("left", function...