score:47
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.
score:2
You can put an onload event at body and put all d3js code in a function. For example:
<body onload="yourFunctionName()">
And in your javascript, insert this:
function yourFunctionName() {
//Your d3js code goes here
}
Just paste the full d3 example code inside this function. The onload event will happen after the DOM is ready.
score:4
The answer marked as correct didn't work for me, and is actually wrong. It's some kind of a hack and should not be considered as a correct answer. Same way you could just execute your code inside setTimeout(function() { .. }, 1000). It is even more reliable as you can set the delay :-/
In my case I needed to wait for all elements to be processed in order to know their actual dimensions. When they are not built, processed and done, the numbers were not correct.
UPDATED. Here is the correct answer:
Most probably you get your data for building DOM using some async call like d3.json() and that's why it takes some time. As async call is non-blocking, then your subsequent code gets invoked even before the async call finishes, causing problems, and this is the reason why you posted this question.
So you are trying to solve this by looking for something in D3 or anywhere else, that would tell you that D3 async call is finished and now you can do your next thing. Some people suggest making sync ajax call. This is awfully WRONG. Async calls are created to be async.
What you actually need to do is to change your paradigm. Just pass a callback to that async call and that's it! Something like that:
function thingsToDoWhenDOMisBuilt() {
...
}
function buildDOM(rootNode, error, thingsToDoWhenDOMisBuilt) {
...
// everything is built, so we can do our post-build thing against DOM
if (thingsToDoWhenDOMisBuilt)
thingsToDoWhenDOMisBuilt()
}
d3.json(urlToData, buildDOM) {
if (error)
console.log("oops")
buildDOM(rootNode, thingsToDoWhenDOMisBuilt)
}
Also, take a look at async.js
Binding events as suggested above is also a horrible idea. You should use .enter() .exit() instead. D3 is Data driven, if you need event-driven flow, then just use jQuery or vanilla JS!
score:5
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");}
);
}
});
Source: stackoverflow.com
Related Query
- Mongo Query: flatten field and split into a new document
- How to use d3 with and express application - reference error: document is not defined
- D3.js: How to get the computed width and height for an arbitrary element?
- What is the difference between svg's x and dx attribute?
- Fast and responsive interactive charts/graphs: SVG, Canvas, other?
- What is the difference between D3 and jQuery?
- Difference between GeoJSON and TopoJSON
- How do I remove all children elements from a node and then apply them again with different color and size?
- How do I save/export an SVG file after creating an SVG with D3.js (IE, safari and chrome)?
- D3 javascript Difference between foreach and each
- Highlight selected node, its links, and its children in a D3 force directed graph
- D3, nested appends, and data flow
- Use D3 and Shiny to implement `identify()` in R
- 3 dimension (X, Y and Z) graph using D3.js
- D3 difference between ordinal and linear scales
- D3 transform scale and translate
- State of SVG Performance on iOS and other Tablets?
- d3.js Map (<svg>) Auto Fit into Parent Container and Resize with Window
- Difference between svg and canvas in d3.js
- Add text label to d3 node in Force directed Graph and resize on hover
- D3 Differentiate between click and drag for an element which has a drag behavior
- How/Where do I get geoJSON data for states, provinces, and administrative regions of non-US countries?
- d3 update data and update graph
- D3js: When to use .datum() and .data()?
- Simple graph of nodes and links without using force layout
- How to properly add and use D3 Events?
- How to use d3.min and d3.max within a d3.json command
- d3.js and document.onReady
- What is the difference between D3.js and Cytoscape.js?
- D3.js binding an object to data and appending for each key
More Query from same tag
- Parameter passing between different JavaScript libraries
- angular.js $apply bottleneck
- update series order in dimple multi-series chart with interactivity
- How to limit animated axis labels position in d3?
- d3.js-adding different colors to one bar in stacked bar chart
- crossfilter dimension not rendering the counts
- sgVizler - Remove Base URL
- Showing a list of events in a D3 map
- More efficient way to handle Mouseevent
- Update Histogram Bins with html range slider
- nesting JSON with d3v4 .stratify()
- Filling two overlapping areas in d3.js
- preprocessing data for d3.js
- Resize Line Graph in D3 based on Window size
- D3 Chord Diagram Google Chrome
- D3.extent() does not give the right range
- How to change the Speed of a force-directed graph in d3.js?
- Animate Pie chat with new data push through API in Angular 8
- d3 force on removing a node remove associated edges
- D3.js version 5 chart to PDF
- Uncaught TypeError: Object [object Array] has no method 'nodes'
- How should i use nested data in d3js
- Trigger d3 event within Jasmine spec test
- angular d3 not rendering uniquely with *ngFor
- Rickshaw AJAX with two endpoints
- D3: Is it possible to add multiple (more than 2) edges between nodes?
- d3.js treemap with 10,000 nodes
- Data with custom date dimple.js
- d3.js - maintain interaction with use of canvas
- Binding Data from tutorial example