Friday, October 06, 2006

Multiple DHTML trees on a page with dynamic ids

I have written before about XBEL and DHTML, Unobtrusive DHTML, and the power of unordered lists and D.D. de Kerf's Easy DHTML TreeView. My previous DHTML tree implementation (derived from D.D. de Kerf's DHTML tree) made use of JavaScript's this keyword to toggle folders. I have extended this method to include "Expand/Collapse" support. We have seen expand and collapse before in Matt Kruse's DHTML Tree. However, I have chosen a slightly different approach inspired by Random Content Order script.

The id of the tree is still used for expand/collapse (via getElementById()). The difference with this technique is that JavaScript now generates the tree id. This means we can have multiple DHTML trees on a page with expand/collapse buttons that do not interfere with each other without any special preliminary HTML preparation being necessary.

An HTML element id is supposed to be unique on a page. The key benefit of this method is that we no longer need to ensure a unique id is assigned to each unordered tree list in the HTML. My new technique is particularly useful where pages may contain several instances of a DHTML tree. These could be rendered as a result of aggregating content from multiple sources (like a portal does). Uniqueness of id is now a random affair taken care of by the JavaScript.

Additionally, the expand/collapse buttons themselves are attached using JavaScript therefore if it is not enabled they will not even appear. Note also that all the trees share the same JavaScript and CSS file.

My new DHTML tree implementation.

Look at the static source code and you will see that each tree starts out with identical HTML markup. A useful tip is to use JSLint to help debug JavaScript. My DHTML tree was initially behaving a little strangely on IE and I have found that Microsoft's script debugger is not very good. Incidentally, a designer has helped me with graphics (Thanks Ben).


ismjml said...

Is the code for this component freely available?
Note: Comment imported. Original by Kal website: at 2008-12-22 15:54

ismjml said...

Yes it is. I would not go so far as to call it a component (as that make me think of jQuery and the like). You can get it here. See the demo source code for further details. Mark
Note: Comment imported. Original by markmc website: at 2008-12-22 22:57