Thursday 23 June 2011

Expand Collapse Tree structure using js and jquery

The following code illustrates the creation of tree expand and collapse using js and jquery.The input passed here is through the xml.


<html>
    <head>
        <title> Sample Tree Structure</title>
        <script type="text/javascript" src="jquery-1.2.6.js"> </script>
        <script>
            var XMLDoc = new ActiveXObject("Microsoft.XMLDOM");
            XMLDoc.load("College.xml");

            function makeTree(){
                var classNode=XMLDoc.getElementsByTagName("class1");
                alert(classNode.length);
                var treeElement=document.getElementById("treeDiv");
                var rowId  = treeElement.rows.length;
                var tr     = treeElement.insertRow(rowId)
                var td = tr.insertCell();

                for(var i=0;i<classNode.length;i++){
                    for(var j=0;j<classNode[i].childNodes.length;j++){
                        var rowId  = treeElement.rows.length;
                        var tr     = treeElement.insertRow(rowId)
                        var td = tr.insertCell();
                        if(j==0){
                            if(classNode[i].childNodes.length>1)
                                td.innerHTML="<li><B><img src='colapse.GIF' onClick='showChildElements(this)'>"+classNode[i].childNodes[j].text+"</B>"
                            else
                                td.innerHTML="<li><B>"+classNode[i].childNodes[j].text+"</B>"


                        }
                        else{
                            td.innerHTML="<span class='dummy' style='display:none'><li>"+classNode[i].childNodes[j].text+"</span>"
                            td.se
                            td.align="center";
                        }
                    }
                }

            }

            function showChildElements(obj){

                if($(".dummy").css("display")=='none'){
                    $(".dummy").css("display","block");
                    obj.src="exp.gif";
                }
                else
                {
                    $(".dummy").css("display","none");
                    obj.src="colapse.gif";
                }

            }

        </script>
    </head>
    <body onLoad="makeTree()">
        <table id="treeDiv" border=1 width="8%">
        </table>
    </body>
</html>



Sample XML:
----------------

<?xml version="1.0" ?>
   <College>
         <class1>
                 <course>
                      java
                  </course>
                 <subcourse>j2ee</subcourse>
                 <subcourse>jmx</subcourse>
                 <subcourse>jsp</subcourse>

        </class1>
   </College>
 


The XMLDOM  I'm using is in particular to I.E  and  also the js can be totally replaced with jquery.excuse me for styles and formattings.


Cheers !! ;-) 

No comments:

Post a Comment