theamateurdataanalyst
theamateurdataanalyst

Reputation: 2834

d3.js not being referenced property in HTML

I currently have the following html.

<!DOCTYPE html>
<html>
  <head>
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script>
      var circle = d3.selectAll("circle");
      circle.style("fill", "steelblue");
      circle.attr("r", 30);
    </script>
  </head>
  <body>
    <svg width="720" height="120">
      <circle cx="40" cy="60" r="10"></circle>
      <circle cx="80" cy="60" r="10"></circle>
      <circle cx="120" cy="60" r="10"></circle>
    </svg>
  </body>
</html>

For some odd reason when I open the html. I don't get the simple results I expect. Anyone have idea why?

Upvotes: 2

Views: 35

Answers (1)

lhoworko
lhoworko

Reputation: 1191

The problem is that the script is running before the dom is loaded. There are a couple of fixes, the simplest being to move the script to the end of the body.

<html>
    <head>
        <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    </head>
    <body>
        <svg width="720" height="120">
            <circle cx="40" cy="60" r="10"></circle>
            <circle cx="80" cy="60" r="10"></circle>
            <circle cx="120" cy="60" r="10"></circle>
        </svg>

        <script>
            var circle = d3.selectAll("circle");
            circle.style("fill", "steelblue");
            circle.attr("r", 30);
        </script>
    </body>
</html>

http://jsfiddle.net/46r21pn1/

Upvotes: 1

Related Questions