I've made a tree view using php/javascript. I just can't figure out how to make it pre-collapsed, on page load.
here is the code, come with the ideas.
<?php
$query=mysql_query("SELECT tree_entry_lang.entry_id, tree_entry_lang.lang, tree_entry_lang.name, tree_entry.parent_entry_id FROM tree_entry,tree_entry_lang WHERE tree_entry.entry_id=tree_entry_lang.entry_id AND lang='eng'");
$numrows=mysql_num_rows($query);
if($numrows>0){
echo "<ul >";
while($row=mysql_fetch_assoc($query)){
echo "<li><img src='..\images\expand.gif' class='collapsableTree' > ".$row['name'];
getChildren($row['entry_id']);
}
echo "</ul>";
}
else echo "Empty base";
function getChildren($parent_id){
$query=mysql_query("SELECT tree_entry_lang.entry_id, tree_entry_lang.lang, tree_entry_lang.name, tree_entry.parent_entry_id FROM tree_entry,tree_entry_lang WHERE tree_entry.entry_id=tree_entry_lang.entry_id AND parent_entry_id=".$parent_id);
$numrows=mysql_num_rows($query);
if($numrows>0){
echo "<ul >";
while($row=mysql_fetch_assoc($query)){
echo "<li><img src='..\images\expand.gif' class='collapsableTree' > ".$row['name'];
getChildren($row['entry_id']);
}
echo "</ul>";
echo "</li>";
}
}
And here is the jQuery part:
$('.collapsableTree').click(function () {
$(this).parent().children().toggle();
$(this).toggle();
});
As I've said, when the page loads, I need all my nodes to be closed. I presume some JavaScript function should be used, But I'm afraid I cant make one. Any solutions ?
Very simple using CSS. Add some classes to the elements.
Then in css:
This isn't something supported by vanilla HTML/jQuery, you'll need to write a plugin to handle it. It's not a trivial task. I suggest taking a look at
jstree
, it's very full-featured and well documented.EDIT
If all you're trying to do is hide the children, why not simply initialize them to
display:none
in CSS. Then show them when clicked. Otherwise, given your example above, make sure you wait until the DOM is ready before you try to bind the event handler by wrapping your statement in$(function(){...})
: