Reputation: 13
How do I have D3 related commands in an external js file.
When I put these commands in tag inside tag of index.html, it works. However when I move these cmds into an external js file, it doesn't work. Did I miss something or it's not possible to call D3 from another js file.
//this works
<body>
<script>
var svg = d3.select("body").append("svg");
svg.attr("width", 250);
svg.attr("height", 250);
var rect = svg.append("rect");
rect.attr("x", 50);
rect.attr("y", 50);
rect.append("style", "fill:blue");
rect.attr("width", 80);
rect.attr("height", 80);
</script>
</body>
//this doesn't work
//inside bhha.js.
//bhha.js is called from <script> tag in the main html
var svg = d3.select("body").append("svg");
svg.attr("width", 250);
svg.attr("height", 250);
var rect = svg.append("rect");
rect.attr("x", 150);
rect.attr("y", 150);
rect.attr("width", 20);
rect.attr("height", 20);
Upvotes: 0
Views: 863
Reputation: 955
If you added your external JS file in <head>
it might not work. If you put your external JS script in <body>
, it would work. Try below, it worked for me:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.2/d3.min.js"></script>
</head>
<body>
<script src="bhha.js"></script>
</body>
</html>
Upvotes: 3