In jstree how to bring a specified node into focus on a large tree?

riketscience picture riketscience · Apr 10, 2015 · Viewed 8.1k times · Source

I have a large jstree structure to implement a taxonomy manager. I have no problem opening a specific node by id: treeElement.jstree('open_node', nodeId);

I have written a search box and when I select an item from the search dropdown it opens an edit box for this item. However the tree, which persists in view down the left hand panel, does not focus on this item. I can open the selected node, but it may be off-screen as it could be in a different part of the tree from the currently visible selection (it's all in a big scroll area).

My Question: How can I make it so that the tree focuses on the desired node? The user needs to actually see where in the tree their selected node resides. I don't want to have to scroll up or down to find it. This seems fairly standard but I cannot find an answer anywhere. Thanks!

Answer

vakata picture vakata · Apr 17, 2015

Use the get_node function with the asDom parameter set to true, and then focus, like so:

treeElement.jstree(true).get_node(nodeId, true).children('.jstree-anchor').focus();

Keep in mind the node must be visible (in the DOM) for this to work.

If the node is not visible (one of its parents is closed), you can use the internal _open_to function to reveal it (and you can also focus it here to keep it simple):

treeElement.jstree(true)._open_to(nodeId).focus();

Best regards, Ivan