Archiv der Kategorie ‘ui‘

 
 

jQuery Tree

There are a whole bunch of different ways to create Trees in jQuery. Here is an example of one of the more simplistic ways to go about it.

First, lets see the tree (we’ll add rollovers later):

Here is the html for the tree:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div id="tree">   
  <ul>
    <li><span>FolderA</span>
      <ul>
        <li>file1.php</li>
        <li>file2.php</li>
        <li>file3.php</li>
      </ul>
    </li>
    <li><span>Folder2</span>
      <ul>
        <li>file1.html</li>
        <li><span>data</span>
          <ul>
            <li>data.xml</li>
            <li>data.json</li>
            <li>data.csv</li>
          </ul>
        </li>
        <li>readme.txt</li>
      </ul>
    </li>
    <li><span>Folder3</span>
      <ul>
        <li>test.js</li>
        <li>experiments.js</li>
        <li>example.html</li>
      </ul>
    </li>
  </ul>
</div>

Pretty straight forward. To make this list act like a tree we need very little jQuery code:

1
2
3
4
5
6
7
8
9
10
11
$(function(){
 
  $("#tree li ul").hide();
 
  $("#tree span").toggle(function(){
    $(this).next().slideDown();
  }, function(){
    $(this).next().slideUp();
  });
 
});

First we wrap everything in $(function(){}) which won’t get run until the DOM is ready. Next we hide all ul elements that are nested within li elements. For all the span elements within the #tree div, we add a toggle event that will slide up or slide down the next element. So for this:

<li><span>Folder3</span>
  <ul>
    <li>test.js</li>
    <li>experiments.js</li>
    <li>example.html</li>
  </ul>
</li>

The span element is clicked and the ul (the “next” element) is either hidden or shown using slideDown or slideUp. Thats it… we’ve got our tree…

There are a bunch of different ways to add mouseover/out events to the tree. One easy way is to wrap the text that you want to add a mouseover/out event to in a span or an anchor tag. You might think you could just add rollover events to the li tags, but that won’t work because some li tags have nested elements within them. So we change the span tags to look like this:

<span><a>Folder3</a></span>

and the li tags too look like this:

<li><a>example.html</a></li>

… then we add some more jQuery stuff:

1
2
3
4
5
6
7
8
9
10
11
$("#tree a").mouseover(function(){
  $(this).css("color", "#8fbbd9");
}).mouseout(function(){
  $(this).css("color", "white");
})
/*
// comment in if you want to alert the text that you are clicking
.click(function(e){
  alert($(e.target).text());
});
*/

Now, when we mouseover and mouseout an anchor tag that is inside the tree div, the text within the anchor tags will change color like this:

To get the full source for either tree just right click them and view the frame source.