Many months ago I ran into a nice JavaScript library for dynamic tree renderings, but it took me forever to learn how to customise it properly. Which is a shame because once you do, it is actually pretty helpful. So I decided to dedicate a few posts to using and configuring d3-mitch-tree. Everything will be available on my Github repo as usual.
This tutorial is part of the following series
- d3-mitch-tree: Create a Basic Tree
- d3-mitch-tree: Add custom body CSS
1 – Setup
First things first, let’s just build a very basic tree. In your working directory, create the following file structure:
. ├── css │ ├── d3-mitch-tree.css │ └── d3-mitch-tree-theme-default.css ├── js │ ├── d3-mitch-tree.js │ └── simple_tree.js └── simple_tree.html
You can download the css files d3-mitch-tree.css and d3-mitch-tree-theme-default.css directly from my Github repo here: for some reason the ones in the original documentation did not work very well for me. Similarly, you can download d3-mitch-tree.js from my repo.
2 – Simple_tree.js
Now this file will contain your tree in JSON format. For this first post, it is going to be a very basic tree
var data = { "id" : 1, "title" : "A", "value" : 1.1, "children": [ { "id" : 2, "title" : "B", "value" : 2.1 }, { "id" : 3, "title" : "C", "value" : 2.2 } ] };
3- Simple_tree.html
There are two interesting blocks in the HTML document:
- Declaring the <div> that will contain the tree (id=”my_tree” in this example)
- Actually creating a d3.mitchTree object and setting the data source to data (from var data = … of simple_tree.js above)
This is what simple_tree.html looks like
<html> <head> <title>Simple JavaScript Tree</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/d3-mitch-tree.css"> <link rel="stylesheet" href="css/d3-mitch-tree-theme-default.css"> <script src="js/d3-mitch-tree.js"></script> <script src="js/simple_tree.js"></script> </head> <body> <!-- div that will contain the tree --> <div id="my_tree" style="width:800px;height:500px;border:1px solid grey;"></div> <script> // Create a new d3.mitchTree object and set the data source var treePlugin = new d3.mitchTree.boxedTree() .setData(data) // the data variable comes from simple_tree.js .setElement(document.getElementById("my_tree")) .setIdAccessor(function(data) { return data.id; }) .setChildrenAccessor(function(data) { return data.children; }) .setBodyDisplayTextAccessor(function(data) { return data.value; }) .setTitleDisplayTextAccessor(function(data) { return data.title; }) .initialize(); </script> </body> </html>
Testing
Now, in your browser, open the file simple_tree.html. This is how it should look like
Now this is not bad, but again still very basic. I will be creating additional posts in the next few weeks to explain how to customize the tree. Also from next time we will be using more acceptable JavaScript/HTML standards, so the code will look a bit more complex, but this is the gist of it 🙂