JavaScript Tree View

A tree view is a fairly common UI component. There were lots of implementations of it that I found that relied on Angular, jQuery, or even Dojo. They all were good solutions, but felt heavy for what I wanted them to do. I just wanted a simple tree view without all the bells and whistles that many of them tacked on.

I decided to write my own JavaScript tree view. Meaning that it can be used with any library you decided to use. It also has a small snippet of CSS that comes along with it just to give it structure. I did not do much in the way of making it stylish. I’ll leave that up to you to get it to look how you want. I did that so it doesn’t clash with any theme you already have setup on your site.

I uploaded a sample page to the repo, but I’ll also outline it here.

HTML

Make sure to bring in the CSS and the JS file. Other than that, it only needs an element with an ID to load into.

 JavaScript

Once the page is setup, creating the tree is simple. The constructor takes two arguments. The first one being a an object that represents the tree structure to create. I’ll go over the aspects of that. The second is the ID of the element to load the DOM into.

Here’s an example tree structure.

At least, each object needs a name and children property. The name is the text to be displayed for the node. Children is an another tree structure to add children to the node. Hopefully that makes sense.

Last to not least, we create an instance of the tree view, using the ID from the div in the HTML.

If you got everything setup correctly using the data I put here, you should get something that looks like this.

JavaScript Tree VIew

JavaScript TreeView

Events

One thing I added to the tree view was the ability to attach some event handlers. There’s a collapse, expand, and select event. You can attach handlers using the on syntax.

There’s a third parameter that will specify what this will be in the callback. You can also detach handlers using off. Pass in the name and the same handler and it will remove it.

Repo

I’ve got a Github repo setup. I’m working on adding tests but if you have any issues or questions, hit me up on Twitter or create an issue on the Github page.

Github repo.


Update 12/22/2015: Here’s a live codepen using the example from the post.