tgunn
tgunn

Reputation: 935

js document conflicting with D3.js - no d3js tools are working

I am trying to experiment with D3.js, however my code only works when contained in tags in the HTML parent document - and not if I contain my JavaScript in an external JS document (i.e. script.js):

In index.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>D3js Test</title>
  <link href="styles/style.css" rel="stylesheet" />
  <script src="scripts/d3.v3.min.js"></script>
  <script src="scripts/script.js" type="text/javascript"></script>
</head>
<body>

</body>
</html>

And I am trying to do something extremely simple

In script.js

var spaceCircles = [30, 70, 110];

var svgContainer = d3.select("body").append("svg")
                                .attr("width", 200)
                                .attr("height", 200);

var circles = svgContainer.selectAll("circle")
                      .data(spaceCircles)
                      .enter()
                      .append("circle");

var circleAttributes = circles
                   .attr("cx", function (d) { return d; })
                   .attr("cy", function (d) { return d; })
                   .attr("r", 20);

Anyone have an idea about what I am missing?

Thanks, TG

EDIT Thanks to @Carlos487 I did manage to get it to work - but it required referencing jQuery and containing everything in a doc ready command. I feel like this shouldn't be necessary...

Upvotes: 0

Views: 210

Answers (3)

Plato
Plato

Reputation: 11052

here is a non jquery way to run the script (or more accurately, to run the portion of your script that depends on having html elements like body existing) after everything else is loaded

//script.js
document.addEventListener('DOMContentLoaded', myInit);
function myInit(){
  var spaceCircles = [30, 70, 110];
  var svgContainer = d3.select("body").append("svg")
  ...
};

Upvotes: 1

Carlos487
Carlos487

Reputation: 1489

Have you try putting all this code inside a $(document).ready(), you have to add jquery but you will get sure everything is loaded correctly before executing anything

Upvotes: 1

Matti
Matti

Reputation: 106

Probably the <body> of the HTML has not yet loaded when you are trying to manipulate it in the external file script.js, which is loaded before the <body> already in the <head>. Try moving the reference to script.js inside the <body> tag, just before the closing </body>. Placing Javascript in the end of HTML files is also generally good practice from perfomance point of view.

Upvotes: 1

Related Questions