toggle entire tree only by a simple button in jstree

I know that is ways to open and close entire tree with two different element in jstree jquery plugin like this :

$(document).ready(function () {

$treeview = $('#jstree-container');

    $treeview.jstree({
        "core": {
            'data': [
  {
    "id": 1,
    "text": "Root node",
    "children": [
      {
        "id": 2,
        "text": "Child node 1",
        "children": [
          {
            "id": 4,
            "text": "Child node 4"
          },
          {
            "id": 5,
            "text": "Child node 5"
          }
        ]
      },
      {
        "id": 3,
        "text": "Child node 2",
        "children": [
          {
            "id": 7,
            "text": "Child node 7"
          },
          {
            "id": 8,
            "text": "Child node 8"
          }
        ]
      }
    ]
  }
],
            "check_callback": true,
            "animation": 200,
            "dblclick_toggle": false,
            "themes": {
                responsive: true,
                "dots": true,
                "icons": true
            }
        },
        "plugins": ["checkbox", "dnd", "contextmenu", "search"],
        "search": {
            "show_only_matches": true,
            "show_only_matches_children": true
        },
        "checkbox": {
            "whole_node": false,
            "tie_selection": false //??? ?????? ?? ???? ??? ???? ??? ? ?? ???? ??? ?????
        }
    });



$('#collapse-all').click(function () {
  $treeview.jstree('close_all');
});
$('#expand-all').click(function () {
  $treeview.jstree('open_all');
});
  });
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet"/>

<a href="#" id="expand-all">open all</a>
|
<a href="#" id="collapse-all">close all</a>

<div id="jstree-container"></div>

But how can I open and close entire tree with a button so that with click on it if tree is open be closed and if it closed , open it ?

Answers 1

  • I found the solution . this is code that I should be used :

    $treeview = $('#jstree-container');
    
        $('#expand-compress').click(function () {
            if ($('.jstree-open',$treeview).length){
                $treeview.jstree('close_all');
            }else{
                $treeview.jstree('open_all');
            }
        });
    

Related Articles