jsTree is a neat little tool that provides a tree interface in the browser. This is great for browsing images and other media.
Here is a basic example to get you started with jsTree. This example makes AJAX requests to a server. The server responds with JSON, which is used to populate the tree.
I provided extra comments to explain what I’m doing here.
<div id="tree-browser"></div>
<script>
//This is how the tree browser gets initialized.
$('#tree-browser').jstree({
'core' : {
'data' : function(node, datacb) {
//This function gets called when a folder is expanded
//Pass an array of objects to datacb to populate the folder
var req_folder = node.id;
if (node.id.startsWith('#') {
req_folder = 'root';
}
$.ajax({
type: 'GET',
url:'/folder-contents',
dataType: 'json',
data: { requested_folder: req_folder }
}).done(function(result) {
if (result.success != 'true')
throw "Request for folder contents failed";
var files = result.data.contents;
var i, file_list = [];
for (i = 0; i < files.length; i++) {
var file = files[i];
file_list.push({
'id': file.public_id,
'parent': node.id,
'icon': file.icon, //custom icon url for the node
'text': file.name, //node text
'children': file.is_folder,
//extra data can be stored in the 'data' field
'data': {
'url': file.file_url
}
});
}
datacb.call(this, file_list);
});
}
}
});
</script>
That’s all there is to it. Happy coding!
