Create jsTree In a Simple Way

Introduction

 
jsTree is jquery plugin that provides interactive trees. It is absolutely free and open source. jsTree is easily extendable, themable and configurable, it supports HTML & JSON data sources, and AJAX loading.
 

Core Features in jsTree

  1. Drag & drop support
  2. Keyboard navigation
  3. Inline edit, create and delete
  4. Fuzzy searching
  5. Customizable node types

Overview 

 
Download jsTree or use CDNJS
 
If you choose to download - all the files you need are in the dist/folder of the download
 
If you use CDNJS, then add the below css and script files.
 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
 
Include jQuery
 
jsTree requires 1.9.0 or greater in your webpage. You can use a CDN version or include a local copy.
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
 
Setup a container
 
This is the element where you want the tree to appear, a <div> is enough. This example has a nested <ul> as there is no other data source configured (such as JSON).
 
<div id="jstree_example"></div>
 
How to create jsTree instance
 
Once the DOM is ready you can start creating jsTree instances.
 
$('#jstree_example').jstree({ })
 
How to Configure the instance
 
We can configure the instance by including themes, plugins and more.
  1. $('#jstree_example').jstree({  
  2.   "core" : {  
  3.     "themes" : {  
  4.       "variant" : "large"  
  5.     }  
  6.   },  
  7.   "plugins" : [ "wholerow""checkbox" ]  
  8. });  
Populate tree using HTML
 
jsTree can turn a regular unordered list into a tree. The minimal required markup is a <ul> node with some nested <li> nodes with some text inside.
  1. <div id="jstree_example">  
  2.   <ul>  
  3.     <li>Root node 1</li>  
  4.     <li>Root node 2</li>  
  5.   </ul>  
  6. </div>  
  7.    
You should have a container wrapping the <ul> and create the instance on that container. Like so: $('#jstree_example').jstree();
 
Populating the tree using JSON
 
jsTree needs a specific format to work with JSON. In the standard syntax no fields are required - pass only what you need.
 
Keep in mind you will be able to access any additional properties you specify - jsTree won't touch them and you will be able to use them later on (using the original property on each node).
 
To change the icon of the node use the icon property.
 
Specifying a string containing a / will display that image as the node icon. Using any other string will apply that class to the <i> element that is used to represent the icon.
 
You can use boolean false to make jsTree render the node with no icon.
 
You can set the state on a node using the state property.
 
Use any combination of the following: opened, selected, disabled.
 
Both li_attr and a_attr are passed directly to jQuery's attr function.
 
When using AJAX set children to boolean true and jsTree will render the node as closed and make an additional request for that node when the user opens it.
 
Any nested children should either be objects following the same format, or plain strings (in which case the string is used for the node's text and everything else is autogenerated).
  1. // Expected format of the node (there are no required fields)  
  2. {  
  3.    id : "string" // will be autogenerated if omitted  
  4.    text : "string" // node text  
  5.    icon : "string" // string for custom  
  6.    state : {  
  7.       opened : boolean // is the node open  
  8.       disabled : boolean // is the node disabled  
  9.       selected : boolean // is the node selected  
  10.    },  
  11.    children : [] // array of strings or objects  
  12.    li_attr : {} // attributes for the generated LI node  
  13.    a_attr : {} // attributes for the generated A node  
  14. }  
Using the alternative JSON format
  1. $('#jstree_example').jstree({  
  2.  'core' : {  
  3.     'data' : [  
  4.       { "id" : "ajson1""parent" : "#""text" : "Simple root node" },  
  5.       { "id" : "ajson2""parent" : "#""text" : "Root node 2" },  
  6.       { "id" : "ajson3""parent" : "ajson2""text" : "Child 1" },  
  7.       { "id" : "ajson4""parent" : "ajson2""text" : "Child 2" },  
  8.     ]  
  9.   }   
  10. });  

Listening for events

 
jsTree triggers various events on the container.
 
To get more information about the event inspect its data argument.
 
In most cases where a node is involved you will get the whole node object passed in. If you get an ID string somewhere and want to inspect the node just use .get_node(). The internal node object is very similar to the JSON format used for loading, but has a few extra properties, which might be useful: Children is an array of all the IDs of the node's immediate children, children_d is an array of all the IDs of the node's descendants, parent is the IDs of the node's parent and parents is an array of all the IDs of the node's ancestors.
 
Please keep in mind that by default all modifications to the tree are prevented (create, rename, move, delete). To enable them set core.check_callback to true. 
 
Below are refresh, select and delete functionality which triggers the event
 
$('#jstree_example').jstree(true).refresh()
$('#jstree_example').jstree('select_node', node)
$("#jstree_example").jstree(true).delete_node(node) 
  1. $('#jstree_example').jstree({  
  2.     "core": {  
  3.         "check_callback"true,  
  4.         "data": []  
  5.      },  
  6. }).bind("refresh.jstree"function (e, data) {  
  7.    //triggers when refresh happens  
  8. }).bind("select_node.jstree"function (e, data) {  
  9.    //triggers when select_node called  
  10. }).bind("delete_node.jstree"function (e, data) {  
  11.   //triggers when delete_node called  
  12. })  

Plugins available in jsTree

 
jsTree has some functionality moved out of the core so you can only use it when you need it. To enable a plugin use the plugins config option and add that plugin's name to the array.
 
For example enabling all the plugins can be done this way: (enable only plugins you need)
 
"plugins" : [
   "checkbox",
   "contextmenu",
   "dnd",
   "massload",
   "search",
   "sort",
   "state",
   "types",
   "unique",
   "wholerow",
   "changed",
   "conditionalselect"
]
 
Changed Plugin
 
This plugin adds additional information about selection changes. Once included in the plugins config option, each changed.jstree event data will contain a new property named changed, which will give information about selected and deselected nodes since the last changed.jstree event
  1. $(function () {  
  2.   $("#jstree_example")  
  3.     .on("changed.jstree"function (e, data) {  
  4.       console.log(data.changed.selected); // newly selected  
  5.       console.log(data.changed.deselected); // newly deselected  
  6.     })  
  7.     .jstree({  
  8.       "plugins" : [ "changed" ]  
  9.     });  
  10. });  
Checkbox plugin
 
This plugin renders checkbox icons in front of each node, making multiple selection much easier.
  1. $(function () {  
  2.  $("#jstree_example").jstree({  
  3.   "checkbox" : {  
  4.     "keep_selected_style" : false  
  5.   },  
  6.   "plugins" : [ "checkbox" ]  
  7.  });  
  8. })  
  9.    
Conditionalselect plugin
 
This plugin overrides the activate_node function (the one that gets called when a user tries to select a node) and enables preventing the function invokation by using a callback.
  1. $(function () {  
  2.   $("#jstree_example").jstree({  
  3.     "conditionalselect" : function (node, event) {  
  4.       return false;  
  5.     },  
  6.     "plugins" : [ "conditionalselect" ]  
  7.   });  
  8. });  
Contextmenu plugin
 
This plugin makes it possible to right click nodes and shows a list of configurable actions in a menu.
  1. $(function () {  
  2.   $("#jstree_example").jstree({  
  3.      "core" : {  
  4.        // so that create works  
  5.        "check_callback" : true  
  6.      },  
  7.     "plugins" : [ "contextmenu" ]  
  8.   });  
  9. });  
Drag & drop plugin
 
This plugin makes it possible to drag and drop tree nodes and rearrange the tree.
  1. $(function () {  
  2.   $("#jstree_example").jstree({  
  3.     "core" : {  
  4.       "check_callback" : true  
  5.     },  
  6.     "plugins" : [ "dnd" ]  
  7.   });  
  8. });  
Sort plugin
 
This plugin automatically arranges all sibling nodes according to a comparison config option function, which defaults to alphabetical order. 
  1. $(function () {  
  2.   $("#jstree_example").jstree({  
  3.     "plugins" : [ "sort" ]  
  4.   });  
  5. });   
State plugin
 
This plugin saves all opened and selected nodes in the user's browser, so when returning to the same tree the previous state will be restored.
  1. $(function () {  
  2.   $("#jstree_example").jstree({  
  3.     "state" : { "key" : "demo2" },  
  4.     "plugins" : [ "state" ]  
  5.   });  
  6. });  
Types plugin
 
This plugin makes it possible to add predefined types for groups of nodes, which means to easily control nesting rules and icons for each group.
 
To set a node's type you can use set_type or supply a type property with the node's data.
  1. $(function () {  
  2.   $("#jstree_example").jstree({  
  3.     "types" : {  
  4.       "default" : {  
  5.         "icon" : "glyphicon glyphicon-flash"  
  6.       },  
  7.       "demo" : {  
  8.         "icon" : "glyphicon glyphicon-ok"  
  9.       }  
  10.     },  
  11.     "plugins" : [ "types" ]  
  12.   });  
  13. });  
Whole row plugin
 
Makes each node appear block level which makes selection easier. May cause a slow down for large trees in old browsers. 
  1. $(function () {  
  2.   $("#jstree_example").jstree({  
  3.     "plugins" : [ "wholerow" ]  
  4.   });  
  5. });  
We have seen the features in jsTree from the above description. Now we will see how to create jsTree instance and load dynamic data to them.
 
JS
 
Let's say, we are fetching the tree data from database and the results are as below:
 
 ClassID  ClassName  StudentID     StudentName
 1  Class1  101  Srinath
 1  Class1  102  Thangabalu
 2  Class2  201  Krishna Vinoth
 2  Class2  202  Sivanesan
 2  Class2  203  Bommuraja
 
We are planning to load the jsTree with PARENT as ClassID and CHILD as StudentID.
 
We can create jsTree nodes using json array or either we can use create_node event from jsTree
 

CREATE jsTree INSTANCE

 
using json array 
  1.    $(document).ready(function () {  
  2.         fnLoadJsTreeInstance()            
  3.     })  
  4.     function fnLoadJsTreeInstance() {  
  5.         var treeDataSource = fnGetTreeData()  
  6.         //jsTree instance  
  7.         $('#divJsTreeExample').jstree({  
  8.             "core": {  
  9.                 "data": treeDataSource  
  10.             },  
  11.             "types": {  
  12.                 "folder": {  
  13.                     "icon""fa fa-folder"  
  14.                 },  
  15.                 "file": {  
  16.                     "icon""fa fa-file"  
  17.                 }  
  18.             },  
  19.             "plugins": ["types"]  
  20.         }).bind('ready.jstree'function (e, data) {  
  21.             $('#divJsTreeExample').jstree('open_all')  
  22.         })  
  23.     }  
  24.     function fnGetTreeData() {  
  25.         var treeData = [  
  26.         { ClassID: 1, ClassName: 'Class1', StudentID: 101, StudentName: 'Srinath' },  
  27.         { ClassID: 1, ClassName: 'Class1', StudentID: 102, StudentName: 'Thangabalu' },  
  28.     { ClassID: 2, ClassName: 'Class2', StudentID: 201, StudentName: 'Krishna Vinoth' },  
  29.       { ClassID: 2, ClassName: 'Class2', StudentID: 202, StudentName: 'Sivanesan' },  
  30.       { ClassID: 2, ClassName: 'Class2', StudentID: 203, StudentName: 'Bommuraja' }  
  31.         ]  
  32.         //now loop through the treeData  
  33.         var treeFinalResult = []  
  34.         var distinctClassID = {}  
  35.         $.each(treeData, function (i, data) {  
  36.             if (!distinctClassID[data.ClassID]) {  
  37.                 //if classID not exists in the object then create a parent  
  38.                 distinctClassID[data.ClassID] = true //make classID to true in the object  
  39.                 //parent node  
  40.                 treeFinalResult.push({  
  41.                     id: data.ClassID,  
  42.                     parent: "#",  
  43.                     text: data.ClassName,  
  44.                     type: "folder"  
  45.                 })  
  46.                 //child node  
  47.                 treeFinalResult.push({  
  48.                     id: data.StudentID,  
  49.                     parent: data.ClassID,  
  50.                     text: data.StudentName,  
  51.                     type: "file"  
  52.                 })  
  53.             } else {  
  54.                 //child node  
  55.                 treeFinalResult.push({  
  56.                     id: data.StudentID,  
  57.                     parent: data.ClassID,  
  58.                     text: data.StudentName,  
  59.                     type: "file"  
  60.                 })  
  61.             }  
  62.         })  
  63.         return treeFinalResult  
  64.     }  
Please note that every node should have an unique id. Parent is the value to group the items.
 
using create_node event 
 
Pass the id and name to the create_node method which will trigger the event where it's bound in jsTree.
  1. // '#' represents the parent. So class will be created as parent node  
  2. $('#jstree_example').jstree(true).create_node('#', {  
  3.         id: data.ClassID,  
  4.         text: data.ClassName,  
  5.         type: "folder"  
  6.      }, "last"function (node) {  
  7.             $('#jstree_example').jstree('open_all')  
  8. })  
  9.   
  10. // 'data.ClassID' represents the parent. So students will be created under Class  
  11. jsTree.create_node(data.ClassID, {  
  12.          id: data.StudentID,  
  13.          text: data.StudentName,   
  14.          type: "file"         
  15.      }, "last"function(node) {  
  16.                $('#jstree_example').jstree('open_all')  
  17.  })  
The above code will create a parent and child and triggers the create_node event. Now the node will be generated visually, but we have bound the node to the jsTree datasource.
  1. $(document).ready(function(){  
  2.     fnLoadJsTreeInstance()  
  3. })  
  4.   
  5. function fnLoadJsTreeInstance(){  
  6.     //jsTree instance  
  7.     $('#jstree_example').jstree({  
  8.         "core": {  
  9.             "data": []  
  10.         },  
  11.         "types": {  
  12.             "folder": {  
  13.                 "icon""fa fa-folder"  
  14.             },  
  15.             "file":{  
  16.                 "icon""fa fa-file"  
  17.             }  
  18.         },  
  19.         "plugins": ["types"]  
  20.     }).bind("create_node.jstree"function (e, data) {  
  21.         //create node will be added to the datasource  
  22.         data.instance.settings.core.data.push( data.node )  
  23.         data.instance.refresh()  
  24.     }).bind("loaded.jstree"function (e, data) {  
  25.         //this will trigger when jstree is loaded  
  26.         //we call the api method here  
  27.     })  
  28. }  

Summary 

 
To load the jsTree, the main thing is to create the valid json(treeData). Then id & parent should be mapped correctly. Please post your queries if anything needs to be clarified.

Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles