Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html collapsed/expanded tree

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.

like image 634
Alexandru Severin Avatar asked Apr 28 '14 14:04

Alexandru Severin


People also ask

How do you expand and collapse a div in HTML?

The . collapse class indicates a collapsible element (a <div> in our example); this is the content that will be shown or hidden with a click of a button. To control (show/hide) the collapsible content, add the data-toggle="collapse" attribute to an <a> or a <button> element.

What is the expand collapse button?

This pattern creates a button that toggles an element as hidden (collapsed) or not hidden (expanded). The element's current state and changes in the element's state are communicated to screen reader users.


3 Answers

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.

like image 112
James Duffy Avatar answered Oct 20 '22 15:10

James Duffy


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/

like image 37
Irvin Dominin Avatar answered Oct 20 '22 17:10

Irvin Dominin


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

like image 37
Solon Avatar answered Oct 20 '22 17:10

Solon