Imagine you have worked hard to make your tables look good, but one thing keeps bugging you; the alignment of the text in table cells. For example, you would like to align the contents of each cell on the comma character. Unfortunately, no browser supports aligning table cells on characters. This is where the jQuery Text Alignment Plugin comes in; it adds support for aligning text based on characters to all browsers.
Assuming your table looks somewhat like the one below:
| Employee | Jan | Feb | Mar |
|---|---|---|---|
| John Cleese | 16,2 | 10,12 | 1,12 |
| Graham Chapman | 12,8 | 16,5 | 14,6 |
| Terry Gilliam | 14,21 | 8,3 | 1,5 |
| Eric Idle | 18 | 3,14 | 0,571 |
| Terry Jones | 9,32 | 12,85 | 1,4 |
| Total | 70,53 | 50,91 | 19,191 |
The following code example shows how to use the jQuery column cell selector and the jQuery text alignment plugins to select the cells of the last three columns and align them on the comma character.
var myCells = $('table#example td');
myCells.nthCol(1).textAlign(',');
myCells.nthCol(2).textAlign(',');
myCells.nthCol(3).textAlign(',');
Alternatively, you could also use the column selector, which is slightly less efficient, but nonetheless a valid way of selecting all three columns. It is however a good idea to get into the habit of re-using elements you have previously selected, as seen in the above example.
$('table#example td:nth-col(1)').textAlign(',');
$('table#example td:nth-col(2)').textAlign(',');
$('table#example td:nth-col(3)').textAlign(',');
Both ways will result in the following table:
| Employee | Jan | Feb | Mar |
|---|---|---|---|
| John Cleese | 16,2 | 10,12 | 1,12 |
| Graham Chapman | 12,8 | 16,5 | 14,6 |
| Terry Gilliam | 14,21 | 8,3 | 1,5 |
| Eric Idle | 18 | 3,14 | 0,571 |
| Terry Jones | 9,32 | 12,85 | 1,4 |
| Total | 70,53 | 50,91 | 19,191 |
Note that cells without the align character are aligned as if they ended with the character. The text as a whole is aligned according to the inherited text alignment property (left in this case.) More details and API documentation can be found on the jQuery text alignment plugin website.