Deselect selected treenode JStree - jQuery

Cedric Berlanger picture Cedric Berlanger · Feb 27, 2014 · Viewed 13.4k times · Source

Situation

When my page is loaded and my treeview is visible, no treenode is selected. When I click on a node, it's selected, which is default behavior.

Question

How can I deselect the node while clicking on the same node? So I want to click on a selected node to deselect it. I have been searching into the documentation. But the event 'select_node' will first select the node before I can check for it's selectstatus.

I know there is a way to deselect a node with code when I click on a button but that's not what I want. I want to click the already selected node.

How can I do this?

Link(s)

Documentation events JStree: http://www.jstree.com/api/#/?q=.jstree%20Event&f=enable_node.jstree

Answer

fletch picture fletch · May 21, 2014

This issue popped up for me today. I expected at least a configuration option that could be set when initializing the tree. While it's not pretty, this is what I did to circumvent the issue:

var _selectedNodeId;
$("#myTree").on("select_node.jstree", function (e, _data) {
    if ( _selectedNodeId === _data.node.id ) {
        _data.instance.deselect_node(_data.node);
        _selectedNodeId = "";
    } else {
        _selectedNodeId = _data.node.id;
    }
}).jstree();

Essentially, I am tracking the selected node and checking this against the node that has been clicked. The downside of this method is that if you have a callback firing on "changed.jstree" it will fire twice, since you are "selecting" first and then "deselecting" if it's already selected.