I'm just getting started with d3.js and there is one detail which is completely eluding me: how do I have my code execute only after the DOM is ready to receive input?
I could, of course, use something like jQuery but that seems excessive.
In every d3.js example I've encountered there seems to be no special document.onReady()
type of routine, yet all the examples work flawlessly. When testing code on my end, however, the code totally fails if executed before the DOM is ready (throwing my code into a window.onload
confirms this).
What gives?
You'll notice in their examples that their javascript is below any of the html elements that is utilized so that part of the dom is loaded before it starts executing the javascript.
Simply putting your javascript at the bottom of the body is usually good enough.
Sometimes you can't rely on the DIV / HTML element placing, for instance when you need to insert the element manipulated with D3 dynamically into the document. In such situations one solution is to monitor the document for DOMNodeInserted events and insert the D3 code in a callback (I believe this rules out IE versions prior to 9 though). Here's an example with jQuery:
$(document).bind('DOMNodeInserted', function(event) { if (event.target.id == "viz") { var sampleSVG = d3.select("#viz") .append("svg:svg") .attr("width", 100) .attr("height", 100); sampleSVG.append("svg:circle") .style("stroke", "gray") .style("fill", "white") .attr("r", 40) .attr("cx", 50) .attr("cy", 50) .on("mouseover", function() { d3.select(this).style("fill", "aliceblue"); }) .on("mouseout", function() { d3.select(this).style("fill", "white");} ); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With