I have the following code which is generating the dynamic tree structure in ul li tag using PHP (Codeigniter).
Following is the PHP code where I am fetching data from preorder traversal table:
function renderTree($tree, $currDepth = -1) {
$currNode = array_shift($tree);
$result = '';
// Going down?
if ($currNode['depth'] > $currDepth) {
// Yes, prepend <ul>
$result .= '<ul>';
}
// Going up?
if ($currNode['depth'] < $currDepth) {
// Yes, close n open <ul>
$result .= str_repeat('</ul>', $currDepth - $currNode['depth']);
}
// Always add the node
$result .= '<li>' . $currNode['name'] . '</li>';
// Anything left?
if (!empty($tree)) {
// Yes, recurse
$result .= renderTree($tree, $currNode['depth']);
}
else {
// No, close remaining <ul>
$result .= str_repeat('</ul>', $currNode['depth'] + 1);
}
return $result;
}
print renderTree($tree);
And it will generate the following tree structure according to the records in table:
<ul>
<li>Language</li>
<li>
<ul>
<li>PHP</li>
<li>Java</li>
<li>
<ul>
<li>Hybernet</li>
</ul>
</li>
<li>Web</li>
<li>
<ul>
<li>HTML</li>
<li>
<ul>
<li>HTML Canvas</li>
</ul>
</li>
</ul>
</li>
<li>Ruby</li>
</ul>
</li>
</ul>
Now I want to use Jquery tree plugin for animating it. Means I can hide and expand the parent-child of it same like explorer or any hierarchical tree module. But because of this generating dynamically I am facing problem on it and not getting how can I configure it with jquery. I need help on it. Thanks in advance.
Used the TreeMenu.js and follow their documentation. Its easy for configuration:
put id="tree" on your UL
Assuming you are using http://jquery.bassistance.de/treeview/demo/
then put some js along the lines of
<script type="text/javascript">
$(function() {
$("#tree").treeview({
collapsed: true,
animated: "fast",
prerendered: true,
persist: "location"
});
})
</script>
it should just work ok , be sure to read the docs and examples from the jquery plugin site linked.
I don't know if this will help you but I've made a jsfiddle for you with expand/collapse categories. You can do it yourself without using any plugin, but again I don't know if that is what you want
CSS
div.tree ul li {
display:block;
}
div.tree ul li ul {
display:none;
}
HTML
<div class="tree">
<ul>
<li>Language <a href="#">expand</a>
<ul>
<li>PHP</li>
<li>Java
<ul>
<li>Hybernet</li>
</ul>
</li>
<li>Web
<ul>
<li>HTML
<ul>
<li>HTML Canvas</li>
</ul>
</li>
</ul>
</li>
<li>Ruby</li>
</ul>
</li>
<li>Other menu <a href="#">expand</a>
<ul>
<li>Other submenu</li>
</ul>
</li>
</ul>
</div>
JS
$(function(){
$('.tree ul li a').click(function(){
var a = $(this).next('ul');
if(a.css('display') == 'block') {
a.css('display','none');
$(this).html('expand');
} else {
a.css('display','block');
$(this).html('collapse');
}
});
});