Haven’t you thought about making your tables expandable? Recently I stumbled to a very interesting and incredibly useful (in my opinion) plugin – jExpand, the plugin perfectly reduces the amount of information on the visitor’s page. jExpand is truly ultra lightweight (only 11 lines of code) jQuery plugin that will make your tables expandable. Typically for business applications, this feature can help you organize your tables better. Therefore, tables can contain more information such as videos, images, diagrams, lists and other elements.
The result of our lesson is as follows:
Step 1 – HTML
The main idea is to reserve two table rows for every entity: the first row contains some basic information, the second row contains additional details. Details row is toggled by clicking on the main (parent) row. Your table can contain as many columns as you need. There is only one important thing – that the additional details row has to span (using colspan attribute) all the columns that main row contains (in case if you need to have full details row area). In the example below, our table contains 5 columns and additional details rows spans exactly 5 columns.
01 |
< table id = "example_table" > |
03 |
< th >Column header 1</ th > |
04 |
< th >Column header 2</ th > |
05 |
< th >Column header 3</ th > |
06 |
< th >Column header 4</ th > |
07 |
< th >Column header 5</ th > |
Step 2 – Javascript
In order to turn the table into the expandable table, we have to connect the jExpand plugin:
1 |
< script type = "text/javascript" src = "jExpand.js" ></ script > |
And then – initialize the plugin:
1 |
$( '#example_table' ).jExpand(); |
If you have a look into the plugin sources, you will find that it’s code is rather simple:
02 |
$.fn.jExpand = function (){ |
04 |
$(element).find( "tr:odd" ).addClass( "odd" ); |
05 |
$(element).find( "tr:not(.odd)" ).hide(); |
06 |
$(element).find( "tr:first-child" ).show(); |
07 |
$(element).find( "tr.odd" ).click( function () { |
08 |
$( this ).next( "tr" ).toggle(); |
The logic of work is very simple: Firstly, it adds .odd class to every odd row in the table (for simplier table styling), then it hides all other (not .odd) rows with our additional content. Then it shows the first table row. Finally, it adds onclick event handler to all .odd rows (with basic info). By clicking on the odd row, it toggles the visibility of related details row (even rows). Short and clear.
[sociallocker]
[/sociallocker]