Wednesday, April 6, 2011

>> TreeView with JavaScript

In this post I will describe how a TreeView type widget can be implemented in HTML/CSS and JavaScript. For the JS part we use jQuery. However similar results can be reached without any JavaScript library.
Let us begin by making a simple html page that have initial menu items in an unordered lists :

HTML:

<ul id="tree_root">
 <li> <a href="javascript:;"> Root Item 1 </a>
<ul>
 <li> <a href="javascript:;"> Sub Item 1.1</a></li>
 <li> <a href="javascript:;"> Sub Item 1.2</a></li>
 <li> <a href="javascript:;"> Sub Item 1.3</a></li>
</ul>
</li>
 <li> <a class="expanded" href="javascript:;"> Root Item 2 </a>
<ul>
 <li> <a href="javascript:;"> Sub Item 2.1</a>
<ul>
 <li> <a href="javascript:;"> Sub Sub Item 2.1.1</a></li>
 <li> <a href="javascript:;"> Sub Sub Item 2.1.2</a></li>
 <li> <a href="javascript:;"> Sub Sub Item 2.1.3</a></li>
</ul>
</li>
 <li> <a href="javascript:;"> Sub Item 2.2</a></li>
 <li> <a href="javascript:;"> Sub Item 2.3</a></li>
</ul>
</li>
 <li> <a href="javascript:;"> Root Item 3 </a>
<ul>
 <li> <a href="javascript:;"> Sub Item 3.1</a></li>
 <li> <a href="javascript:;"> Sub Item 3.2</a></li>
 <li> <a href="javascript:;"> Sub Item 3.3</a></li>
</ul>
</li>
</ul>
 
CSS: It is time to add styles to live up our interactive tree. We need two 
general styles. One is ‘expandable’ which will be assigned to all items 
that have sub-items. The other one is ‘expanded’ which will indicate 
that the item is expanded (what a surprise :)  ). 
#tree_root a {
 background-repeat:no-repeat;
 text-decoration:none;
 padding-left:20px;
 height:20px;
 display:block;
 line-height:20px;
}
#tree_root a.expandable {
 background-image:url(../images/plus.png);
}
#tree_root a.expanded {
 background-image:url(../images/minus.jpg);
} 
 
Javascript (jQuery): Next task is to add the functionality. Here we will use this little JS:
$(document).ready(function(){
 $("#tree_root a").each(function(){
  if ($(this).parent().find("ul").length>0) {
   $(this).addClass("expandable").parent().children("ul").hide();
   if ($(this).hasClass("expanded")) {
    $(this).parent().children("ul").show();
   };
  } ;
 });
 $("#tree_root a.expandable").click(function(){
  $(this).toggleClass("expanded").parent().children("ul").toggle();
 });         
}); 
 
 
 
You can view the Final result here: http://psd2htmldev.com/blogExamples/TreeView/treeview.html 

No comments:

Post a Comment