Back to the index of articles and examples

Row Expansion with plain HTML

So, you want an expandable table, well, maybe YUI's DataTable is not for you. This is only a brief sample not really meant for a final application though it can be the basis for one. If you want nested DataTables, you may not actually need real YUI DataTables, perhaps not even HTML tables. This table has been created with the following code:

Where the uppercase variables are as follows, plus a couple of extra ones which we'll use later:

See YQL DataSource for an explanation of what the YQLSubstitute function does. In a nutshell, it will fill the HTML element referenced in the first argument with the YQL statement given in the second using the templated in the third argument.

The third argument is the key here, it applies that template to each row received replacing the field names inside the curly braces with the value of that field for each row. Now, this is obviously not a DataTable and it is not even an HTML table, it is a unordered list smartly formatted. All that set of <li> elements will go into the element in the first argument, which has been defined thus: <ul id="list"></ul>

The first element in that template, the div with class="trigger" contains the icon signaling that the row can be expanded. The id of that row has the primary key for the artist table, with a leading letter to make it a valid identifier, which can later be used to fetch the albums for that artist, with this code:

I set a listener for a click anywhere in the list. If the target happens to have the className of "trigger" then it really was the trigger cell and I start paying attention. First, I stop the bubbling and any default action associated with clicking. I fetch both the row where the trigger is and what I assume might be the custom rows added, which should be the very last element in the current row.

If I find thisRow is collapsed by checking the className, then I set it to expanded. I check whether the customRow is really such because it should have the right className. If it is not, what I got there is a regular element within thisRow so I need to create that customRow, mark it with the correct className so I can identify it later, and append it to the current row. Finally, I fill the custom row the same way I filled the original one using a different query and template.

If the row was expanded, in the last } else { I mark it as collapsed. The custom row is set to have display:none when nested within a collapsed row.

It is not much of a deal to nest a further level by adding another trigger icon on these added rows and adding to the click event listener to tell apart clicks on the outer level from clicks in the nested rows. The CSS styles also need some polishing. I leave all this as an exercise to the reader.