Posts Tagged ‘javascript’


2 Mar 2013

To use the latest version of D3, you need to use charset="utf-8" in the call to <script>.

I’m giving a talk at ENAR in just over a week, on interactive graphics. My slides (still in preparation) are on the web.

The slides were working fine locally on my laptop, but they weren’t working on my web server…I was getting a syntax error regarding an illegal character.

I figured out that I needed to add charset="utf-8", like so:

<script charset="utf-8" type="text/javascript" src="js/d3.js">

D3.js difficulties

8 Feb 2013

I’m pleased with my progress learning javascript and D3. (I’m actually writing coffeescript rather than javascript.)

But I spent a lot of time thrashing about yesterday, due mostly to two silly errors.

Put the script in the body

First, I’d tried to make a truly simple example, making just an SVG with a little rectangle.

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <title>Put script in body</title>
    <script type="text/javascript" 

    <script type="text/javascript">
    var h=50;
    var svg ="body").append("svg")
                .attr("height", h).attr("width", h);
    svg.append("rect").attr("x", 0).attr("y", 0)
                .attr("height", h).attr("width",h);


But this gives nothing. You need to move the script from the head to the body, as it is here. Then it works.

I don’t really understand this. Perhaps I should go back to my reading.

[Update: I think I’ve figured this out. If you put the script in the head, the code gets run before the body exists, and so there’s no body in which to append the SVG. Conclusion: Put the link to your script at the very bottom of the html file.]

Don’t forget enter()

In D3, you bind data to a bunch of objects, and attributes of the objects can be controlled by features of the data. I write code sort of like this:

   .attr("x", (d) -> start[d])
   .attr("width", (d) -> end[d] - start[d])
   .attr("height", (d) -> hInner)
   .attr("fill", (d) -> color[d])
   .attr("stroke", "none")

My most common mistake so far: I forget the .enter() part. You don’t get a error message, but the objects don’t get created.