Jquery – Jstree Open specific branch on load

jqueryjsonjstree

I'm having trouble finding a way to open a specific JS tree branch on load. My current tree is loaded through Ajax and thus shows only the top level, all other branches are loaded via Ajax when expanded. What I want is if the user loads the page at a certain place in the tree then I want the tree to load with that branch open on the tree.

I'm pretty sure I can add this to the JSON by passing the children part into the JSON for that specific node. However how do I load the tree with that branch already open?

I can perform an after load function which will open nodes that I specify but these feels a little messy, is there a way to open the branch on load?

My current function which loads the tree via JSON is this:

$.jstree.defaults.core.data = true;
$('.nav-tree').jstree({
    'core' : {
        'data' : {
            'url' : function (node) {
              return host+ "treeNavigation?format=json";                        
            },
            'data' : function (node) {
                return node.id === '#' ? { 'rootid' : 0} : {'rootid' : node.id};
            }
        }
    },
    "plugins" : [
        "wholerow"
    ]
});

Best Answer

I found that the result was in the JSON being returned. By adding extra data we were able to open the tree on load to specific place within its tree.

The data we added to the JSON was:

"state" : { "opened" : true, "selected" : true}

Where as before if a node had children we would use "children" : true if a node was opened further down then we would add the children details in place of true.

So as an example our data returned looked like this:

{
"id" : "1",
"Text" : "folder 1",
"state" : {"opened" : true, "selected" : true },
"children" : [{
    "id" : "1.1"
    "text" : "folder 1.1"
    "children" : true
    },
    {
    "id" : "1.2"
    "text" : "folder 1.2"
    "children" : false
    } 
    } ]
}

The above specified that the folder with ID 1 should be open and show the below children 1.1 and 1.2. 1.1 would be a node that had children and would open upon select.

Related Topic