Question

I am using d3js in a django web app. I have a static js script that contains a function to render a visualization given some data (passed in the context) and a selection (e.g. histogram(data,selection)). Why would d3 ignore the passed selection and directly append to the body?

This is a simplified version of my code.

Template:

{% load staticfiles %}
<script type="text/javascript" src="{% static 'd3.js' %}"></script>
<script src="{% static 'myd3vis.js' %}"></script>
<body>
 <div class="vis"></div>
 ...
</body>   
<script type="text/javascript">
 mselection = d3.select(".visualization")
 data = {{data|safe}}
 histogram(data,selection)
</script> 

In myd3vis.js file I define the histogram(data,selection) function, which contains something like this:

svg = console.append("svg").attr({"class":"visualization",
       "width": 100,
       "height":200}) 
...

When the template loads, the visualization svg is always appended to the body, instead of being appended to the <div class="vis"> element. Any idea why this would happen?

Was it helpful?

Solution

In most browsers’ JavaScript environments, console is a global object unrelated to the DOM – it provides debugging functions (e.g. console.log())… unless you’re clobbering it with a d3 DOM selection elsewhere, console.append() is unlikely to behave the way you seem to think it will.

Replace console with a bona-fide d3 selection, like:

var svg = d3.select('div.vis').attr(…); // et cetera

and inspect this object, to ensure your DOM logic is sound.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top