O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.2. Navigating with a File-Tree Expander

Problem

On content-heavy sites with multiple tiers of information architecture, occasionally a need arises to present several levels of nested data. If all of the info was presented in its entirety, it would be too unwieldy to be useful and would take up too much vertical space on a page. Enter the file-tree paradigm. This functionality, seen most notably in the desktop UI of Windows Explorer (not to be confused with Internet Explorer), allows a user to expand and compact layers of directories.

Solution

By using jQuery’s descendant selectors on nested unordered lists, we can hide/show additional portions of a tree structure, as needed. This is done by adding class="tree" to the top-level unordered list and using a combination of CSS and JavaScript to unveil its sublevels, producing a tree like that in Figure 13-2. Additionally, we make use of event delegation to support numerous tiers without the overhead of attaching event listeners to multiple elements. Instead, the event is captured at the top level of the <ul class="tree"> via jQuery’s .live() method.

Presenting multiple levels of data through a file tree

Figure 13-2. Presenting multiple levels of data through a file tree

File tree—HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us"> <head> <meta ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required