0

I know this is a super easy question. But I am apparently missing something super obvious. I just want to create an svg element with D3 and see it on my page. My index.htmllooks like this:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="node_modules/d3/dist/d3.min.js"></script>
        <script src="selections.js"></script>
        <link rel="stylesheet" href="style.css">
        <title>D3 Selections</title>
    </head>

    <body>
    </body>

</html>

Whereas my selections.js looks like this:

console.log("This appears...")

w = window.innerWidth
h = window.innerHeight

// // make the svg

const svg = d3.select("body")
    .append("svg")
    .attr("height", h)
    .attr("width", w)
    .attr("class", "svg")

The first console.log() is still visible in the console. But I cant see the svg. I know I am missing something super clear, but I just cant see it at the moment:/

Lenn
  • 1,283
  • 7
  • 20
  • 2
    You can do as the current answer proposes, or you could simply move `selections.js` to the bottom of the ``, then there will be something for D3 to select and append the SVG. – Gerardo Furtado Sep 01 '21 at 12:48
  • Thank you very much! Is this a common thing to do with D3? I imagine that when your D3 code gets a little bigger it might be a bit annoying to have it all in a script tag?! – Lenn Sep 02 '21 at 05:38
  • 1
    No, nothing to do with D3 specifically, this is the way browsers work, have a look here: https://stackoverflow.com/q/17106462/5768908 – Gerardo Furtado Sep 02 '21 at 06:12
  • 1
    Regarding your second question, it's a good idea using external scripts. – Gerardo Furtado Sep 02 '21 at 06:20

1 Answers1

1

I don't know d3.js that well but you should probably wait for the DOM to load:

console.log("This appears...");

w = window.innerWidth;
h = window.innerHeight;

document.addEventListener('DOMContentLoaded', e => {
  // // make the svg
  const svg = d3.select("body")
    .append("svg")
    .attr("height", h)
    .attr("width", w)
    .attr("class", "svg");
});
chrwahl
  • 8,675
  • 2
  • 20
  • 30
  • Thank you very much, this works:)! I am really confused when I can do what in JS – Lenn Sep 01 '21 at 07:03
  • 1
    @Lenn `addEventListener()` is more flexible. If you assign something to `window.onload` more times they will overwrite each other. With the event listener you can have multiple. – chrwahl Sep 01 '21 at 07:04