I'm new to d3 and having trouble accessing an element from the DOM after my visualization has loaded on the page. I'm trying to change the attribute of a rectangle element, but for a reason I do not understand I can only do this in the browser's js console and not in the html file with a script.
After reading up here on stackoverflow, I found this link suggesting that the accepted answer to my problem is to put the js code at the 'bottom of the body' which I'm assuming means that I could also put it after the closing html tag. So, I've tried putting the script after the close of the html tag and have even used the window.onload
method but neither seem to work.
I feel like I'm missing something here on a fundamental level but I am also relatively new to javascript. Here is the code:
<html>
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
function draw(data) {
var width = 960,
height = 420;
var colorScale = d3.scale.category20c();
var treemap = d3.layout.treemap()
.padding(4)
.size([width, height])
.value(function(d) { return d.size; });
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append('g')
.attr('class','chart');
var cell = svg.data([data]).selectAll("g")
.data(treemap.nodes)
.enter().append("g")
.attr("class", "cell")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
cell.append("rect")
.attr("width", function(d) { return d.dx; })
.attr("height", function(d) { return d.dy; })
.style("fill", function(d) { return colorScale(d.name); });
cell.append("text")
.attr("x", function(d) { return d.dx / 2; })
.attr("y", function(d) { return d.dy / 2; })
.attr("text-anchor", "middle")
.text(function(d) { return d.name+" "+d.size+"%"; });
};
</script>
</head>
<body>
<script type="text/javascript">
d3.json("https://dl.dropboxusercontent.com/s/3csp4n28q3lcpqh/data.json", draw);
</script>
</body>
</html>
<script>
window.onload = function ()
{
d3.select("rect").style({fill: "white"});
}
</script>
EDIT:
I found an answer to my problem. Including the d3.select
statement at the end of the draw function allowed me to change the style. I sort of did this earlier but accidentally placed it after the function closure so it wasn't included in the callback. This led me down the path of trying to fix things in a jQuery kind of way by waiting for a ready document.
I created a codepen to share the code and visualization that I was originally working on: http://codepen.io/anon/pen/dGdagR
Despite having found a different solution to my problem, I am still wondering why I can't access the DOM with regular javascript on a ready document. Is this some sort of weird functionality with d3 or another concept I'm not understanding correctly?