Reputation: 6228
I'm using this code to generate a tree in html, and the problem is, everytime I refresh the page the tree expands.
I want to create it so that when I open the page, some branches will be expanded and some collapsed, depending on an attribute it has.
For example:
<span><i class="icon-plus-sign"></i> Parent 1</span>
<ul> childrens go here
</ul>
<span><i class="icon-minus-sign"></i> Parent 2</span>
<ul> childrens go here
</ul>
When I open the page, I want to see Parent 2's children, but not Parent 1's.
I'm novice in html and completely new to css and javascript. So any suggestion would help.
Upvotes: 6
Views: 3555
Reputation: 1387
If I understand correctly, you want to add a class to certain elements which will cause them to be closed upon page load?
The simplest solution would be to add
$(".start-closed").click();
to the bottom of the JQuery and then add the class start-closed
to the nodes you want to close upon page load.
JSFiddle: http://jsfiddle.net/dksNr/
Let me know if I've misunderstood the question.
Upvotes: 3
Reputation: 30993
You can add at the start of the code the close of each element mark as collapsed using its icon class.
Code:
$('.tree li.parent_li > span').each(function(i,e){
if ($(this).find('i').hasClass("icon-plus-sign")){
$(this).parent('li.parent_li').find(' > ul > li').hide();
}
});
Demo: http://jsfiddle.net/q3DQ2/
Upvotes: 1
Reputation: 102
Add the following right after your OnClick function:
//Collapse each node
$('.tree li.parent_li > span').each(function(){
var children = $(this).parent('li.parent_li').find(' > ul > li');
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
});
With that it will go through each node and hide it.
One more way to do it would be to have it by default be hidden with:
style="display: none;"
on each node you want hidden
Upvotes: 1