C3: Uncaught TypeError: Cannot read property 'width' of undefined

Created on 17 Jun 2014  路  6Comments  路  Source: c3js/c3

With the latest release c3 release (download link from main website) and d3.v3.min.js

Google Chrome 36.0.1985.49 beta

I am surprised this doesn't work right out of the box. Am I doing something wrong?

<!DOCTYPE html>
<html>
<head>
  <link href="c3.css" rel="stylesheet" type="text/css">

  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  <script src="c3.js"></script>

  <script>
    var chart = c3.generate({
     data: {
       columns: [
         ['data1', 30, 200, 100, 400, 150, 250],
         ['data2', 50, 20, 10, 40, 15, 25]
       ]
     }
   });
  </script>
</head>
<body>

  <div class='chart'>
  <div id="chart"></div>
  </div>

</body>
</html>

Most helpful comment

try this way to solve problem:
use script inside the body tag like this:
Capture

All 6 comments

Don't ask my why but I played around with your simple example here and this made it work..http://jsfiddle.net/3ryU3/6/. Definitely an interesting result.

If I move the JavaScript to the bottom of 'body' tag it works. Interesting... Can someone please comment as to why this is necessary before I close this issue? Thanks!

Browsers generally execute javascript as soon as it is encountered. This means that this code will execute before the DOM has been parsed the chart div. This will nearly always cause issues.

Having script run ones the DOM is ready is so common that jQuery created some shorthand to wrap your code snippets in.

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="c3.js"></script>
<script>
$(function() {
  console.log( "ready!" );
  var chart = c3.generate({
     data: {
       columns: [
         ['data1', 30, 200, 100, 400, 150, 250],
         ['data2', 50, 20, 10, 40, 15, 25]
       ]
     }
   });
});
</script>

This can now be placed anywhere since it wont be run until the document is ready. Below is the pure javascript way of things.

window.onload = function

@patrickglass Thanks!

this error mainly occurs when your script function load first and then html body so solution is to write script function at the bottom of body so that i will be able to find div id and bind graph to that it

try this way to solve problem:
use script inside the body tag like this:
Capture

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zachallia picture zachallia  路  3Comments

wojciechowskid picture wojciechowskid  路  3Comments

ivarkallejarv picture ivarkallejarv  路  3Comments

jstone-ponderosa picture jstone-ponderosa  路  3Comments

MarcusJT picture MarcusJT  路  4Comments