Novadar
Novadar

Reputation: 96

D3 Javascript -- Example SVG is declared in HTML cannot embed with HTML Tags

Stackoverflow World. Need some guidance. I am working on a D3 JS Script that will be embedded in a packaged application that does not allow ANY native HTML code in the editor -- only JS/JQ. I found a great visualization on Bostock's Blocks (https://bl.ocks.org/mbostock/4063550) (please look at the example for a full single HTML page usage -- I modified it with an inline JSON for testing). After tweaking the code to enhance an inbound JSON block I noticed that in the head of the code the initial SVG is called before the Javascript block. This will not work for me. No matter what I try I cannot seem to get the typical way of instantiating the SVG to work. Here is how the SVG is first referenced:

{<svg width="960" height="1060"></svg>}

Later the SVG is manipulated directly unlike many other Blocks examples

var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + (width / 2 + 40) + "," + (height / 2 + 90) + ")");

All of the examples I find look like this (no matter how I try to match it (after of course removing the 'svg' tag, it does not work.

Here is the way I've seen it many times and I applied that framework in my non-working JS Fiddle.:

    var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

I've tried recreating 'svg' tag via D3 but it never seems to work.

Here is a JSFiddle where it works as written (with the 'svg' html tag):

https://jsfiddle.net/LtL6yu5a/4/

Here is a JSFiddle where it exists like I need it (but not working):

https://jsfiddle.net/bhj9gds1/

Tips, pointers, anything will be helpful. The issue to me seems to be related to the group or "g" item.

Upvotes: 0

Views: 134

Answers (1)

sparta93
sparta93

Reputation: 3854

The reason it is not currently working is because there is no declaration of g in your code and it is being referenced later on.

Instead, you can simply do it like this:

//declare width and height for your svg
var width = 960
var height = 1000;

//append a svg element to the body with the width and height declared above
var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height);

//append g element to svg and set it equal to a var called "g"
var g = svg.append("g").attr("transform", "translate(" + (width / 2 + 40) + "," + (height / 2 + 90) + ")");

JSFiddle - https://jsfiddle.net/0uxeywn5/

Upvotes: 1

Related Questions