Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open one node and all its parents using jstree

Tags:

jstree

I'm trying to use jstree and let one node and all its parent be opened when the page is opened. Here is the html code I used to test.

    <div id="treeTask">
       <ul>
          <li id="node_37"><a href="#">TEST1</a>
              <ul>
                  <li id="node_38"><a href="#">TEST2</a></li>
                  <li id="node_39"><a href="#">TEST3</a></li>
              </ul>
          </li>
      </ul>

      <ul>
          <li id="node_3"><a href="#">TEST1</a>
              <ul>
                  <li id="node_4"><a href="#">TEST2</a></li>
                  <li id="node_6"><a href="#">TEST3</a></li>
              </ul>
          </li>
      </ul>
   </div>

And here is the call to initialize jstree and open the node.

 $(function () { 
        $("#treeTask").jstree();

        $("#treeTask").bind("ready.jstree", function (event, data) { 
            $("#treeTask").jstree("open_node", $("#node_4"));

            if((data.inst._get_parent(data.rslt.obj)).length) { 
                data.inst._get_parent(data.rslt.obj).open_node(this, false); 
              }  
        }); 

  });

I have been manipulating the code for a while, but could not make it work. I would really appreciate if anyone can help.

Thanks so much!

like image 974
Ryan Avatar asked Dec 26 '14 18:12

Ryan


3 Answers

You can use the built-in _open_to function:
http://www.jstree.com/api/#/?q=open_to&f=_open_to%28obj%29

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
  data.instance._open_to('node_4');
}); 
like image 148
vakata Avatar answered Nov 11 '22 01:11

vakata


Based on @maddin solution, I've updated it to support any number of parent levels.

jsFiddle

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
  $("#treeTask").jstree('open_node', 'node_4', function(e,d) {
    for (var i = 0; i < e.parents.length; i++) {
      $("#treeTask").jstree('open_node', e.parents[i]);
    };
  });
}); 

It should be noted that if a node is selected, all its parents will be opened automatically. This would be somewhat equivalent to the above:

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
  $("#treeTask").jstree('select_node', 'node_4');
}); 
like image 34
Goozak Avatar answered Nov 11 '22 00:11

Goozak


Maybe this is an Solution for your problem:

fiddle

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
 $("#treeTask").jstree('open_node', 'node_4', function(e,d) {
     if(e.parents.length){
         $("#treeTask").jstree('open_node', e.parent);
     };
  });
}); 
like image 33
Martin Avatar answered Nov 11 '22 02:11

Martin