Click on any column header to hide a column. Click on the button at right to show all columns or use the drop-down to select which one to show. See comments below.
This example shows an easy way to hide and show columns in a DataTable.
When you click the header of any column, that column will hide.
The DOM elements for the column are still there, but its
style is changed to
It uses a split button to show the hidden columns. If you click the body of the button, all columns hidden will be shown again. You can also use the dropdown of the split button to show individual columns. Columns will reappear in the same order as initially shown, after all, they never actually moved anywhere. The dropdown of the split button is updated with the headings of the hidden columns and the button itself gets disabled when all columns are shown.
I used the YUI Selector component to fetch the cells to be hidden. Each cell in a DataTable gets, amongst many other classNames, one that
is composed of the prefix
yui-dt-col- and then the value of the
key property for the column.
This makes it easy to locate all the cells to be hidden. Then, Dom's
removeClass methods take an
array just like the one that the Selector produces, so these two lines are enough to show/hide columns:
var cells = YAHOO.util.Selector.query('.yui-dt-col-' + column.key, this.getTableEl()); YAHOO.util.Dom.addClass(cells,'hide');
This is the code used to hide each column. The second argument to the Selector
query method is where to start the search,
in this case, in the DataTable
<table> element. The rest of the code is just for managing the split button menu.
It will not work with nested headers.
Thanks to merahul94538 who pointed out that with
pagination enabled this example didn't work so I just added a listener for
refreshEvent to ensure columns are hidden
when rewritten. In fact, the same problem would have happened in many other scenarios where
called, since it can add new rows to the table, which do not have the className to hide columns.
The same issue would happen if the
addRow method is called, the new added row would not have the className set.
You would have to listen to
rowAddEvent. There might be other cases which should be solved in a similar way.
It uses the same PHP server script as the Server driven DataTable example.