Tree Control

Examples

Our icon images are combined into a single png file to reduce HTTP requests.

Custom Icons in the Tree Control

Many implementations of tree-style controls call for using custom icons on a per-node basis. In this example, we'll look at one strategy for apply custom icons to specific nodes using the YUI TreeView Control.

We'll start by using a single image containing our icon set and we'll use the technique known as "CSS Sprites" to specify which icon we want to use for each specific style. This allows us to combine seven images in a single HTTP request (read more about why reducing HTTP requests is a good idea). The raw image is displayed to the right of the tree.

With that image in place, we can now set up our style rules to identify icons for each file type. We do that by positioning our icons.png image uniquely for each icon we want to display:

The effect of these style rules is to create a 20-pixel space to the left of the styled object and to place the icon directly in that space. The sheet of icons is positioned so that, for example, the zip-file icon will appear when the class icon-zip is applied.

To apply these styles on a per-node basis in TreeView, we use the labelStyle property of TextNodes and MenuNodes and the contentStyle property of HTMLNodes.

Here is the code used to create the TreeView instance above and to create the first node, "Ahmed's Documents," while applying the specific icon styles to each node:

The script for creating Susheela's part of the tree is very similar. Here, we'll use HTMLNodes, and we'll use the contentStyle property to apply the icon style:

Note that in this example we're also applying the "folder style" CSS file that is included with the TreeView Control's examples; you can find that file in the YUI distribution under /examples/treeview/css/folders/tree.css.