I plan to use jsTree to visualize tree like structures and I would like to achieve the following behavior:
Constraints:
In other words I want to achieve something similar to a) change the default state of node to 'open' or b) determine if this is the first visualization (probably by examining the 'cookie' plugin attributes if we don't have state persisted) and if so then call 'open_all'
Ideas are appreciated. Thanks!
To expand all nodes, simply use
$("#treeView").jstree("open_all");
You can include it in the initial load, like so
$('#treeView').jstree(
{
"themes": {
"theme": "default",
"dots": false,
"icons": false
},
"plugins": ["themes", "html_data", "checkbox", "ui"]
}).jstree("set_theme", "apple")
.bind("loaded.jstree", function (event, data) {
$(this).jstree("open_all");
});
Likewise, if you want to check all elements, use
$(this).jstree("check_all");
Regarding cookies, I haven't used it, but there is a plugin named jquery.cookie.js
available. I suppose it contains methods to load/save data from/to a cookie. You have to bind another event, such as
.bind("change_state.jstree", function (evt, data) { ... } );
to capture the state-change and the initial loading in the loaded.jstree
event would read from the cookie. Please check out this link to read more about cookie handling, both is mentioned - how you can use it with or without this plugin.
Update: jquery.cookie.js has been superseded by js-cookie, which has the functions Cookies.set('name', 'value')
, var cval = Cookies.get('name');
and Cookies.remove('name');
for cookie handling.
The following snippet, which is a modified jsTree example, has 2 child nodes beneath Root node 2
, which expands immediately after the control is loaded:
$(document).ready(function() {
$('#treeView').jstree({
'core': {
'data': [{
"id": "ajson1",
"parent": "#",
"text": "Simple root node"
},
{
"id": "ajson2",
"parent": "#",
"text": "Root node 2"
},
{
"id": "ajson3",
"parent": "ajson2",
"text": "Child 1"
},
{
"id": "ajson4",
"parent": "ajson2",
"text": "Child 2"
},
]
}
})
.bind("loaded.jstree", function(event, data) {
$(this).jstree("open_all");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="treeView">
</div>