Jon Deaton
Jon Deaton

Reputation: 4409

D3 Chart is not displaying

I know that similar questions like this have been answered before but honestly I have been searching for hours and none of the answers have helped me get a simple D3 image to appear in my browser. I literally just want to display a D3 bar chart in my browser.

Here are my files, which I simply copied and pasted from here.

Index.html

<!DOCTYPE html>
<html>
<script src="https://d3js.org/d3.v3.min.js"  charset="utf-8"></script>
<script src="app.js" type="text/javascript"></script>
<link rel = "stylesheet"
  type = "text/css"
  href = "app.css" />
<div class="chart"></div>
</html>

app.js

var data = [4, 8, 15, 16, 23, 42];

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, 420]);

d3.select(".chart")
    .selectAll("div")
    .data(data)
    .enter().append("div")
    .style("width", function(d) { return x(d) + "px"; })
    .text(function(d) { return d; });

app.css

.chart div {
  font: 10px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}

When I open index.html in the browser (Chrome) I see nothing. I have tried following the instructions from this post and this post but still I see nothing.

How can I get this simple chart to appear? Your help is greatly appreciated.

Upvotes: 1

Views: 5988

Answers (1)

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

Link in your app files by adding these lines to Index.html:

<script src="app.js"></script>
<link rel="stylesheet" href="app.css">

Wrap your D3 code in a DOMContentLoaded event, so that it won't run until the page has loaded:

document.addEventListener('DOMContentLoaded', function(e) {
  var data = [4, 8, 15, 16, 23, 42];

  var x = d3.scale.linear()
      .domain([0, d3.max(data)])
      .range([0, 420]);

  d3.select(".chart")
      .selectAll("div")
      .data(data)
      .enter().append("div")
      .style("width", function(d) { return x(d) + "px"; })
      .text(function(d) { return d; });

});

Upvotes: 3

Related Questions