3

I'm working on the first set of D3 tutorials (found here) and have run into a problem where the first item of the data array doesn't appear. The border i have placed on each data div element indicates that essentially that first entry has "collapsed" into a line up the top. Is there an explanation as to why this is happening? How can I fix this?

My HTML, CSS and JS has been put onto codepen to view and edit.

Thanks in advance!

Isolated JS:

var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ]; 

d3.select(".project") 
  .selectAll(".project__bar-chart")
    .data(data) 
  .enter()
  .append("div") 
    .attr("class", "project__bar-chart")
    .style("width", function(d) {return d + "rem";}) 
    .text(function(d) {return d;}) 
Libby B
  • 33
  • 4

1 Answers1

5

You have this in your HTML:

<div class="project">
  <div class="project__bar-chart"></div>
</div>

Thus, when you do:

d3.select(".project").selectAll(".project__bar-chart")

You are selecting one previously existing <div> in your selectAll, and your "enter" selection will have one element less.

Solution: remove the div with class project__bar-chart:

<div class="project">
    //look Ma, no div
</div>

Here is your Pen: https://codepen.io/anon/pen/bgKxXG?editors=1010

And here is a Stack snippet:

var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ]; //The data that we're working with

d3.select(".project") //bring our focus to the container containing this class
  .selectAll(".project__bar-chart")
    .data(data) //the data is in line 1 
  .enter()
  .append("div") // Shove the data (defined in line 1) into the Div in the HTML
    .attr("class", "project__bar-chart")
    .style("width", function(d) {return d + "rem";}) 
//we're inserting a function in this style attribute to make sure that the width of the div reflects the value given. 
    .text(function(d) {return d;}) //this is what it will look like
.project {
  color: black;
    font: 1rem;
    font-family: sans-serif;
    margin: .1rem:;
    text-align: right;
}

.project__bar-chart {
    background: #be3c3c;
    border: 1px solid #802828
    }
  <head>
    <script src="https://d3js.org/d3.v4.js"></script>
    <script type="text/javascript" src="index.js"></script>
  </head>
  <body>
    <div class="project">
    </div>
Graham
  • 7,431
  • 18
  • 59
  • 84
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171