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 pletely new to css and javascript. So any suggestion would help.
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 pletely new to css and javascript. So any suggestion would help.
Share Improve this question edited Apr 28, 2014 at 14:09 msturdy 10.8k11 gold badges44 silver badges53 bronze badges asked Apr 28, 2014 at 14:01 Alexandru SeverinAlexandru Severin 6,28312 gold badges51 silver badges75 bronze badges 3- I think you should use cookies. – Arbaoui Mehdi Commented Apr 28, 2014 at 14:10
- 3 Looking at your fiddle, it doesn't look like novice work at all.. just saying.. – LifeQuery Commented Apr 28, 2014 at 14:12
- 1 Something like this? jsfiddle/GpdgF/1721 – Spokey Commented Apr 28, 2014 at 14:14
3 Answers
Reset to default 3If 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/dksNr/
Let me know if I've misunderstood the question.
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/q3DQ2/
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