14

I am new to datavis and the D3 library and I'm trying to follow the tut here http://mbostock.github.com/d3/tutorial/bar-1.html

When I run the code, nothing displays on my webpage, can anyone point out the problem??

I think its something to do with the d3.select method. When I run the code and inspect it, the body is empty, so Im assuming nothing is being created. Any help would be hugely appreciated!!!

<title>3Dtut - 1</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.4.5">   </script>

<script type="text/javascript">
var data = [4, 8, 15, 16, 23, 42];  

//container for the bar chart
var chart = d3.select("body").append("div")
.attr("class", "chart");

//adding div elements to the bar chart
 chart.selectAll("div")
     .data(data)
     .enter().append("div")
     .style("width", function(d) { return d * 10 + "px"; })
     .text(function(d) { return d; });
</script>


<STYLE type="text/css">
.chart div {
   font: 10px sans-serif;
   background-color: steelblue;
   text-align: right;
   padding: 3px;
   margin: 1px;
   color: white;
 }
 </STYLE>
</head>
<body>
</body>
</html>
Marcel Korpel
  • 20,899
  • 5
  • 58
  • 79
Daft
  • 8,340
  • 12
  • 52
  • 94

3 Answers3

26

The problem is related to the position of your <script> .. </script> within the html document.

No body element exists yet at the moment that your script is being executed. That means that d3.select("body") will be empty, and no div.chart is being appended.

Try to move your <script> .. </script> inside the <body> .. </body> part. This will guarantee that the body element exists when your code is being executed.

nautat
  • 5,025
  • 30
  • 22
  • you probably also want to mention that the `script` tag should be at the **end** of the body tag, to allow DOM to be fully loaded before the script is executed. – paradite Apr 29 '16 at 14:20
0

Using the inside the body makes it not only available to the tag or any of the but also executes it faster. Also as div is a tag u could create a class eg. one and then use it as d3.select(".one") so that it doesn't coincide.

Vaibhav Magon
  • 1,373
  • 1
  • 10
  • 27
0

If you do not wish to put your <script> tags within the <body> element, you can also tell the browser to execute your d3 code (or any other JavaScript code) after the DOM is ready.

Using a library such as jQuery, you can use:

$( document ).ready(function() {
  // Your d3 code here
});

This will ensure that your scripts are executed after the whole DOM is ready, including the <body> element.

For reference, examples and a shorter version of jQuery ready function, see http://learn.jquery.com/using-jquery-core/document-ready/.

jbmusso
  • 3,307
  • 1
  • 22
  • 35