Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically select a node in jsTree and open all parents

In a multi-level jsTree how do I select a particular node (probably a leaf node) and expand all it's parents? Example:
From this JSFiddle (http://jsfiddle.net/mmeah/fyDE6/) I want to programmatically select Grand Child and have all parent nodes opened.

For some context I'm trying to ensure the user returns to the correct node in the tree if they follow a deep link into my site

like image 974
David Hayes Avatar asked Aug 17 '12 22:08

David Hayes


3 Answers

jsTree gives an open_node() function to arbitrarily trigger any node to open. Just scan the tree for non-open parents and open them.

Example: http://jsfiddle.net/mmeah/yyy8W/

$("#findChild").click(function(){
    $.jstree._reference(myTree).open_node("#Node_001",function(){;},false);
});
$("#findGrandChild").click(function(){
    var closedParents = $("#Node_003").parents("li.jstree-closed");
    for(var i=closedParents.length-1;i>=0;i--){
        pleaseOpen($(closedParents[i]));
    }
});

function pleaseOpen(thisNode){
    if(typeof thisNode=="undefined") return;
    if(thisNode.hasClass("jstree-leaf") || thisNode.hasClass("jstree-open") ) return;
    $.jstree._reference(myTree).open_node(thisNode,function(){;},true);
}

like image 71
MMeah Avatar answered Oct 17 '22 11:10

MMeah


Ah ha, I was on the right track but I had a race condition between my deep linking parsing code and the construction of the tree

To select a node and trigger the event

$("#tree").jstree("select_node", selector).trigger("select_node.jstree");

To do this after the tree has loaded so it works...

$("#tree").jstree(...).bind("loaded.jstree", function () 
{
    $("#tree").jstree("select_node", selector).trigger("select_node.jstree");
});
like image 20
David Hayes Avatar answered Oct 17 '22 11:10

David Hayes


jQuery selection doesn't work on nodes that are not opened [expanded] already. Hence I chose to open [expand] all elements before I did the jQuery selection and then close all the nodes after that.

                // open all nodes to select the desired node using jquery.
                $("#tree").jstree('open_all');
                var node = $("desiredNodeSelector");
                // close all tree since we are done with the selection
                $("#tree").jstree('close_all');

Now all we need is just use the 'select_node' jstree api.

$("#tree").jstree('select_node', node);
like image 1
fantagons Avatar answered Oct 17 '22 10:10

fantagons