D3 combines HTML, CSS, and SVG to create graphics. That means we're going to need an HTML and a JavaScript file. We'll use Chrome Developer Tools to tweak our visualizations and test things out. Let's start with some HTML coding:
<!DOCTYPE html> <title></title> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"> <div id="graph"></div> <script src="http://d3js.org/d3.v3.min.js"></script> <script src="code.js"></script>
These six lines of HTML code are the basics we're going to use throughout this book.
The first two lines comprise a minimal HTML5 document. You no longer need to include the <html>
, <head>
, and <body>
tags. Next is the <link>
tag that pulls in Twitter Bootstrap's CSS rules—a good set of defaults to make things prettier. After that comes the <div>
tag that will hold our visualization, and finally, there's the <script>
tag that loads d3.js.
At the end, we include a code.js
file, where we'll put most of our code. Twitter doesn't offer a hosted version of Bootstrap, so you have to download the whole package from http://twitter.github.com/bootstrap/ and unpack it next to the other files you're working with. All we need now is a server to run everything. This is because we don't want to get into trouble with browser security models when making Ajax requests. Any server will do, but here's a quick way to get one up and running if you already have Python installed (by default on Mac and Linux).
Fire up a console, navigate to your working directory, and run the following command:
$ python -m SimpleHTTPServer
Python will run the SimpleHTTPServer
module as a standalone script and create a fully functional local server.
Now point Chrome to localhost:8000
and fire up the developer console—Ctrl + Shift + J for Linux and Windows and Option + Command + J for Mac. You should see a blank website and a blank JavaScript console with a command prompt waiting for some code:
Chrome Developer Tools are indispensable in web development. Most modern browsers have something similar, but I thought we'd stick to a single example to keep the book shorter. Feel free to use a different browser.
We are mostly going to use the Elements and Console tabs: Elements to inspect the DOM, and Console to play with JavaScript code and look for any problems.
The other six tabs come in handy for large projects. The Network tab will let you know how long files are taking to load and helps you inspect the Ajax requests. The Profiles tab will help you profile JavaScript for performance. The Resources tab is good for inspecting client-side data. Honestly, I have never needed Timeline and Audits before. One of the favorites from Developer Tools is the CSS inspector at the right-hand side of the Elements tab.
It can tell you what CSS rules are affecting the styling of an element, which is very good for hunting rogue rules that are messing things up. You can also edit the CSS and immediately see the results: