Running D3 code on the DOM, ready without jquery

Following the advice of this SO question / answer, I placed my D3 code under the html and inside the function that performed onload, however, when I test this on my local MAMP server, the D3 code does not execute. Please note that if I run runD3codein the console, then the intended histogram will appear, but if I included this code inside the function runD3codein index.html, then the histogram will not appear. I also note that including D3 below html is in how the author of the library does it here .

<!DOCTYPE html>
<meta charset="utf-8">


    <style type="text/css">   
      .chart div {
        font: 10px sans-serif;
        background-color: steelblue;
        text-align: right;
        padding: 3px;
        margin: 1px;
        color: white;
      }
    </style>

  <body onload="runD3code()">
      <div class="chart">

      </div>
        <script src="./d3.js" charset="utf-8">
       <script>
       function runD3code() {
        console.log("not getting called");
         var data = [4, 8, 15, 16, 23, 42];
           d3.select(".chart")
            .selectAll("div")
            .data(data)
          .enter().append("div")
            .style("width", function(d) { return d * 10 + "px"; })
            .text(function(d) { return d; });
        }
        </script>

  </body>

Then I even tried to put it in an equivalent document, but the D3 code still did not start

       (function(){
    var tId = setInterval(function(){if(document.readyState == "complete") onComplete()},11);
    function onComplete(){
        clearInterval(tId);    

         var data = [4, 8, 15, 16, 23, 42];
           d3.select(".chart")
            .selectAll("div")
            .data(data)
          .enter().append("div")
            .style("width", function(d) { return d * 10 + "px"; })
            .text(function(d) { return d; });

        };
})()

Can you suggest a solution to this problem?

+4
1

, html . .

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">

    <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>
    <div class="chart"></div>
    <script src="./d3.js" charset="utf-8"></script>
    <script>
       window.onload = function runD3code() {
        console.log("not getting called");
         var data = [4, 8, 15, 16, 23, 42];
           d3.select(".chart")
            .selectAll("div")
            .data(data)
          .enter().append("div")
            .style("width", function(d) { return d * 10 + "px"; })
            .text(function(d) { return d; });
        };
     </script>

  </body>
</html>
+2

Source: https://habr.com/ru/post/1548577/


All Articles