YUI recommends YUI3.
YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.
This documentation is no longer maintained.
The DataTable control provides a simple yet powerful API to display screen-reader accessible tabular data on a web page. Notable features include sortable columns, pagination, scrolling, row selection, resizeable columns, and inline cell editing.
YUI community member Daniel Barreiro (screen name Satyam) has contributed two terrific articles on the YUI DataTable Control on YUIBlog:
In addition to reading this User's Guide and the canonical DataTable examples by DataTable author Jenny Han Donnelly, we strongly recommend that you review Satyam's work in preparing for your DataTable implementation.
Note: The 2.6.0 release of DataTable introduces the ScrollingDataTable and CellEditor classes, the Paginator widget is now offered as a standalone component, and significant changes have been applied to DataTable's pagination and sorting architectures. While backward compatibility has been maintained whenever possible, the Paginator widget is now an optional dependency, and custom extensions to inline cell editing or server-side pagination and/or sorting will likely need to be updated to be compatible with the new models. Implementers who are upgrading from an earlier version are strongly advised to read the Upgrades Notes.
Users new to DataTable can skip this section and proceed directly to the Getting Started section. Implementers who are upgrading from previous versions should note the following changes for version 2.6.0:
new YAHOO.widget.ScrollingDataTable
. For backward compatibility, a ScrollingDataTable instance will also be returned if {scrollable:true}
is passed to the constructor for DataTable.DataTable.editCheckbox()
has been removed. The CheckboxCellEditor class should be used instead.DataTable.editDate()
has been removed. The DateCellEditor class should be used instead.DataTable.editDropdown()
has been removed. The DropdownCellEditor class should be used instead.DataTable.editRadio()
has been removed. The RadioCellEditor class should be used instead.DataTable.editTextarea()
has been removed. The TextareaCellEditor class should be used instead.DataTable.editTextbox()
has been removed. The TextboxCellEditor class should be used instead.showCellEditorBtns()
has been removed. The CellEditor method renderBtns() should be used instead.editorUpdateEvent
has been removed.resetCellEditor()
has been renamed to destroyCellEditor()
.disable()
and undisable()
) until the callback function is executed to finish the transaction.paginationEventHandler
AttributehandleSimplePagination()
handleDataSourcePagination()
updatePaginator()
showPage()
formatPaginator()
formatPaginationDropdown()
formatPaginatorLinks()
dynamicData
Attribute has been added to better support server-side pagination and/or sorting.onPaginatorChange()
method has been renamed to onPaginatorChangeRequest()
paginated
Attribute and the object literal paginator
Attribute value. Implementers must use the Paginator class to populate the paginator
Attribute.myDataTable.set()
:
MSG_EMPTY
MSG_ERROR
MSG_LOADING
COLOR_COLUMNFILLER
(moved to ScrollingDataTable class)doBeforeShowCellEditor()
now returns true
by default and returns false
to cancel showing the cell editor.minWidth
default value is now null
.maxAutoWidth
.getThLinerEl()
rather than directly accessing the DOM via TH.firstChild.To use the DataTable control, include the following source files in your web page.
<!--CSS file (default YUI Sam Skin) --> <link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.9.0/build/datatable/assets/skins/sam/datatable.css"> <!-- Dependencies --> <script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script> <script src="http://yui.yahooapis.com/2.9.0/build/datasource/datasource-min.js"></script> <!-- OPTIONAL: JSON Utility (for DataSource) --> <script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script> <!-- OPTIONAL: Connection Manager (enables XHR for DataSource) --> <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js"></script> <!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) --> <script src="http://yui.yahooapis.com/2.9.0/build/get/get-min.js"></script> <!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) --> <script src="http://yui.yahooapis.com/2.9.0/build/dragdrop/dragdrop-min.js"></script> <!-- OPTIONAL: Calendar (enables calendar editors) --> <script src="http://yui.yahooapis.com/2.9.0/build/calendar/calendar-min.js"></script> <!-- Source files --> <script src="http://yui.yahooapis.com/2.9.0/build/datatable/datatable-min.js"></script>
<!--CSS file (default YUI Sam Skin) --> <link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.9.0/build/datatable/assets/skins/sam/datatable.css"> <!-- Dependencies --> <script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script> <script src="http://yui.yahooapis.com/2.9.0/build/datasource/datasource-min.js"></script> <!-- OPTIONAL: JSON Utility (for DataSource) --> <script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script> <!-- OPTIONAL: Connection Manager (enables XHR for DataSource) --> <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js"></script> <!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) --> <script src="http://yui.yahooapis.com/2.9.0/build/get/get-min.js"></script> <!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) --> <script src="http://yui.yahooapis.com/2.9.0/build/dragdrop/dragdrop-min.js"></script> <!-- OPTIONAL: Calendar (enables calendar editors) --> <script src="http://yui.yahooapis.com/2.9.0/build/calendar/calendar-min.js"></script> <!-- Source files --> <script src="http://yui.yahooapis.com/2.9.0/build/datatable/datatable-min.js"></script>
yui-skin-sam
class name to an element that is a parent of the element
in which the DataTable Control lives. You can usually accomplish this simply by putting the class on the
<body>
tag:
<body class="yui-skin-sam">
<body class="yui-skin-sam">
For more information on skinning YUI components and making use of default skins, see our Understanding YUI Skins article here on the website.
Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.
Note: If you wish to include this component via the YUI Loader, its module name is datatable
. (Click here for the full list of module names for YUI Loader.)
Where these files come from: The files included using the text above will be served from Yahoo! servers. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug
versions of YUI JavaScript files, please download the library distribution and host the files on your own server.
Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.
DataTable creates an internal ColumnSet object to define the header cells for the <thead>
and an internal RecordSet object to locally hold data for the rows of the table. The ColumnSet is created using the Column definitions passed in via the constructor, and the RecordSet is created using the ColumnSet object and populated with data provided by the DataSource.
<table>
element contains a collection of <tr>
elements. Each <tr>
is assigned a Record instance to display, and its unique DOM ID is assigned its corresponding Record's ID. If the DataTable is paginated, then the <table>
will show only a subset of the entire RecordSet.The markup created for each DataTable instance starts with the implementer-provided container, into which a <table>
element is create. Within the <table>
element, two <tbody>
elements are created: a message <tbody>
element to display stateful messages such as "Loading data..." or "No data found" and also a primary <tbody>
element that contains the cells of data.
In the case of a ScrollingDataTable, there are actually two <table>
elements, each housed in its own container, identified as the "header container" and the "body container". The <table>
in the header container consists of a <table>
element with only a <thead>
element of Column header <th>
s, whose purpose is to remain fixed on the screen when the body cells scroll vertically. The <table>
generated into the body container is nearly identical to the <table>
created by the DataTable class, with the exception of the <thead>
element which is placed offscreen for screenreader consumption only.
The following markup is a generic sample of the DOM elements that are generated by the DataTable class. Note that Column keys are also assigned as CSS class names on DOM elements so they can be used as hooks to skin or customize the UI. As such Column keys are subject to string validation before being used in the DOM or in CSS. Please see the Column Keys Usage section for more information.
<div id="myContainer" class="yui-dt"> <div class="yui-dt-mask" style="display: none;"/> <table summary=""> <colgroup> <col/> <col/> <col/> <col/> <col/> </colgroup> <thead> <tr class="yui-dt-first yui-dt-last"> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-first yui-dt-asc"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header A</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort descending" href="yui-dt0-href-{sanitizedkey}">Header B</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header C</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header D</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-last"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header E</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> </tr> </thead> <caption> DataTable Caption </caption> <tbody class="yui-dt-message" style="display: none;"> <tr class="yui-dt-first yui-dt-last"> <td colspan="5" class="yui-dt-loading"> <div class="yui-dt-liner"> Loading... </div> </td> </tr> </tbody> <tbody tabindex="0" class="yui-dt-data" style=""> <tr style="" id="yui-rec0" class="yui-dt-first yui-dt-even"> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-first yui-dt-asc"> <div class="yui-dt-liner"> Cell A </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell B </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell C </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell D </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-last"> <div class="yui-dt-liner"> Cell E </div> </td> </tr> ... <tr style="" id="yui-rec3" class="yui-dt-last yui-dt-odd"> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-first yui-dt-asc"> <div class="yui-dt-liner"> Cell A </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell B </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell C </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell D </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-last"> <div class="yui-dt-liner"> Cell E </div> </td> </tr> </tbody> </table> </div>
<div id="myContainer" class="yui-dt"> <div class="yui-dt-mask" style="display: none;"/> <table summary=""> <colgroup> <col/> <col/> <col/> <col/> <col/> </colgroup> <thead> <tr class="yui-dt-first yui-dt-last"> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-first yui-dt-asc"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header A</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort descending" href="yui-dt0-href-{sanitizedkey}">Header B</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header C</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header D</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> <th id="yui-dt0-th-{sanitizedkey}" rowspan="1" colspan="1" class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-last"> <div class="yui-dt-resizerliner"> <div id="yui-dt0-th-{sanitizedkey}-liner" class="yui-dt-liner"> <span class="yui-dt-label"> <a class="yui-dt-sortable" title="Click to sort ascending" href="yui-dt0-href-{sanitizedkey}">Header E</a> </span> </div> <div id="yui-dt0-th-{sanitizedkey}-resizer" class="yui-dt-resizer" style="left: auto; right: 0pt; top: auto; bottom: 0pt; height: 24px;"/> </div> </th> </tr> </thead> <caption> DataTable Caption </caption> <tbody class="yui-dt-message" style="display: none;"> <tr class="yui-dt-first yui-dt-last"> <td colspan="5" class="yui-dt-loading"> <div class="yui-dt-liner"> Loading... </div> </td> </tr> </tbody> <tbody tabindex="0" class="yui-dt-data" style=""> <tr style="" id="yui-rec0" class="yui-dt-first yui-dt-even"> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-first yui-dt-asc"> <div class="yui-dt-liner"> Cell A </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell B </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell C </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell D </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-last"> <div class="yui-dt-liner"> Cell E </div> </td> </tr> ... <tr style="" id="yui-rec3" class="yui-dt-last yui-dt-odd"> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-first yui-dt-asc"> <div class="yui-dt-liner"> Cell A </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell B </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell C </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable"> <div class="yui-dt-liner"> Cell D </div> </td> <td headers="yui-dt0-th-{sanitizedkey} " class="yui-dt0-col-{sanitizedkey} yui-dt-col-{sanitizedkey} yui-dt-sortable yui-dt-resizeable yui-dt-last"> <div class="yui-dt-liner"> Cell E </div> </td> </tr> </tbody> </table> </div>
The DataTable API provides a set of methods for implementers to manipulate underlying data and associated DOM elements, such as addRow()
, updateRow()
, and deleteRow()
. Calling addRow(oData)
on the DataTable will add a new Record of data to the end of the RecordSet, and create and populate a new <tr>
element at the bottom of the <table>
element. Calling addRow(oData, i)
will create a new Record of data and a new <tr>
element and insert them into the given index position i
of the RecordSet and <table>
, respectively.
When pagination is enabled, calling addRow()
will always add a Record to the RecordSet, but will only add a <tr>
element to the <table>
if the new Record is in view within the current page. Implementers should keep this in mind when dealing with RecordSet index values, as these values may or may not be equal to <tr>
index values when pagination is enabled.
A DataTable is instantiated by passing in the following to the constructor:
// DataTable constructor syntax var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource);
// DataTable constructor syntax var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource);
Make sure the container element is available in the DOM before instantiating your DataTable, either by placing your script in the HTML body after the markup has been rendered, waiting until the window load
DOM event fires, or by using the Event Utility's onAvailable
method to programmatically create your DataTable as soon as the container element is available.
// Defer instantiation YAHOO.util.Event.addListener(window, "load", function() { var myDataTableDeferred = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource); });
// Defer instantiation YAHOO.util.Event.addListener(window, "load", function() { var myDataTableDeferred = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource); });
The second argument of the DataTable constructor is an array of object literals to define the Columns that are rendered into the table. In the simple example below, we define our DataTable to display three Columns, which we name "fname", "lname", and "age":
var myColumnDefs = [ { key: "fname", label: "First Name" }, { key: "lname", label: "Last Name" }, { key: "age", label: "Age" } ];
var myColumnDefs = [ { key: "fname", label: "First Name" }, { key: "lname", label: "Last Name" }, { key: "age", label: "Age" } ];
The following Column properties are supported:
Property | Type | Description |
---|---|---|
key | String | The unique name assigned to each Column. When a Column key maps to a DataSource field , cells of the Column will automatically populate with the corresponding data. If a key is not defined in the Column definition, one will be auto-generated. Please see the Column Keys section for more uses. |
field | String | The DataSource field mapped to the Column. By default, the field value is assigned to be the Column's key. Implementers may specify a different field explicitly in the Column definition. This feature is useful when mapping multiple Columns to a shared field, since keys must remain unique, or when the field name contains characters invalid for DOM or CSS usage (see the Column Keys section for more information). |
label | String | By default, the <th> element is populated with the Column's key. Supply a label to display a different header. |
abbr | String | Value for the <th> element's abbr attribute. |
children | Object[] | An array of object literals that define nested child Columns of a Column. |
className | String | A custom CSS className or array of classNames to be applied to every cell of the Column. |
editor | String | String pointer to a CellEditor class. |
editorOptions | Object | Object literal CellEditor-specific configuration options. Please refer to the API documentation for more information on which properties are supported for each type of CellEditor. |
formatter | String | HTMLFunction | A function or a pointer to a function to handle HTML formatting of cell data. |
hidden | Boolean | True if Column is hidden. |
maxAutoWidth | Number | Upper limit pixel width that a Column should auto-size to when its width is not set. Please note that maxAutoWidth validation is executed after cells are rendered, which may cause a visual flicker of content, especially on non-scrolling DataTables. |
minWidth | Number | Minimum pixel width. Please note that minWidth validation is executed after cells are rendered, which may cause a visual flicker of content, especially on non-scrolling DataTables. |
resizeable | Boolean | True if Column is resizeable. The Drag & Drop Utility is required to enable this feature. Only bottom-level and non-nested Columns are resizeble. |
selected | Boolean | True if Column is selected. |
sortable | Boolean | True if Column is sortable. |
sortOptions | Object | Object literal of configurations for sort behavior.
|
width | Number | Pixel width. |
The DataTable class and its related classes provides many configuration parameters for you to fine-tune the user experience of your DataTable instance.
Unique Column keys are assets that tie together data consumption and UI rendering in DataTable. When a Column key
maps to a DataSource field
, cells of the Column will automatically populate with the corresponding data. When a key does not map to a DataSource field, the cell will be left blank or can be populated manually, through the use of a formatter.
Column keys are also assigned as classnames to allow CSS hooks for customizing the UI. Defining custom CSS for ".yui-dt-col-myKey" and/or ".yui-dt-col-myKey .yui-dt-liner" lets you easily define styles per Column.
Internal usage of Column keys in the document include element IDs, names, classnames, headers, and href attributes, as well as selectors in dynamically created CSS rules. To support this kind of usage, Column keys must first be sanitized, to strip the string of characters that may be problematic for CSS and DOM usage (i.e., make sure it contains only letters, numbers, hyphen, or underscore). If your DataSource field
contains characters that are invalid for DOM and/or CSS usage, it is recommended that you define the Column key as a simple alphanumeric string and also define a Column field
that points to the problematic DataSource field.
By progressively enhancing <table>
markup that is already on the page,
you can make core content available to end users who do not have
JavaScript enabled, while delivering a fully functional DataTable control to
users who do have JavaScript enabled -- all from the same code base.
To this end, the DataSource accepts an HTML
<table>
element as a source of data. The DataTable will parse
the data out of the table, remove it from the DOM, and replace
it with an enhanced control.
<div id="myMarkedUpContainer"> <table id="myTable"> <thead> <tr> <th>AAA</th> <th>BBB</th> <th>CCC</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>bbb</td> <td>ccc</td> </tr> <tr> <td>2</td> <td>bbb</td> <td>ccc</td> </tr> <tr> <td>3</td> <td>bbb</td> <td>ccc</td> </tr> </tbody> </table> </div>
<div id="myMarkedUpContainer"> <table id="myTable"> <thead> <tr> <th>AAA</th> <th>BBB</th> <th>CCC</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>bbb</td> <td>ccc</td> </tr> <tr> <td>2</td> <td>bbb</td> <td>ccc</td> </tr> <tr> <td>3</td> <td>bbb</td> <td>ccc</td> </tr> </tbody> </table> </div>
var myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("myTable")); myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE; myDataSource.responseSchema = { fields: [ { key: "AAA", parser:"number" }, { key: "BBB" }, { key: "CCC" } ] }; var myColumnDefs = [ { key: "AAA" }, { key: "BBB" }, { key: "CCC" } ]; var myDataTable = new YAHOO.widget.DataTable("myMarkedUpContainer", myColumnDefs, myDataSource);
var myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("myTable")); myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE; myDataSource.responseSchema = { fields: [ { key: "AAA", parser:"number" }, { key: "BBB" }, { key: "CCC" } ] }; var myColumnDefs = [ { key: "AAA" }, { key: "BBB" }, { key: "CCC" } ]; var myDataTable = new YAHOO.widget.DataTable("myMarkedUpContainer", myColumnDefs, myDataSource);
Implementers should note that form elements and elements attached to DOM event listeners may not be parsed correctly. Custom parsers should be used to extract data values out of form elements, and formatters should be used to reconstruct form elements programmatically. Likewise, DOM event listeners will be unattached from the original elements and implementers should listen for the corresponding DataTable Custom Events to rewire any lost functionality.
By default, DataSources with responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE
, iterate over all TR elements of all TBODY elements of the given TABLE to parse out data. If there are any non-data elements (like summary rows or the message TBODY in DataTable), they should first be removed from the DOM.
Out of the box, the DataTable is accessible via screen readers and keyboard-navigable. Please take advantage of the following additional features to further enhance accessibility:
/* Supply abbr values for THs */ var myColumnDefs = [ { label: "Amt Due", abbr: "Amount Due" }, { label: "Rec'd", abbr: "Received" }, { label: "YTD", abbr: "Year to Date" } ]; /* Supply caption and/or summary values for the TABLE */ var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { caption: "My Caption", summary: "My Summary" });
/* Supply abbr values for THs */ var myColumnDefs = [ { label: "Amt Due", abbr: "Amount Due" }, { label: "Rec'd", abbr: "Received" }, { label: "YTD", abbr: "Year to Date" } ]; /* Supply caption and/or summary values for the TABLE */ var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { caption: "My Caption", summary: "My Summary" });
The DataTable class provides a set of built-in static functions to format certain
well-known types of data. In your Column definition, if you set a Column's formatter
to YAHOO.widget.DataTable.formatDate,
that
function will render data of type Date with the default syntax of "MM/DD/YYYY". If you would like to bypass a
built-in formatter in favor of your own, you can point a Column's
formatter
to a custom function that you define.
If you don't define any formatter, DataTable's default formatter will take your cell's data value as markup and insert it into the DOM with innerHTML. If you are using data from a third-party source, user input data, or any other untrustworthy source, it is highly recommended you point to the "text" formatter, which will HTML-escape data values for safer insertion into the DOM. See the Security Considerations section for more information.
As of the 2.3.0 release, the static formatter functions are called within the scope of the DataTable instance. Also as a convenience, the following string shortcuts may be used to point to the built-in formatter functions:
"button"
points to YAHOO.widget.DataTable.formatButton
"checkbox"
points to YAHOO.widget.DataTable.formatCheckbox
"currency"
points to YAHOO.widget.DataTable.formatCurrency
"date"
points to YAHOO.widget.DataTable.formatDate
"dropdown"
points to YAHOO.widget.DataTable.formatDropdown
"email"
points to YAHOO.widget.DataTable.formatEmail
"link"
points to YAHOO.widget.DataTable.formatLink
"number"
points to YAHOO.widget.DataTable.formatNumber
"radio"
points to YAHOO.widget.DataTable.formatRadio
"text"
points to YAHOO.widget.DataTable.formatText
"textarea"
points to YAHOO.widget.DataTable.formatTextarea
"textbox"
points to YAHOO.widget.DataTable.formatTextbox
// Define a custom format function var myFormatDate = function (elCell, oRecord, oColumn, oData) { var oDate = oData, sMonth; switch(oDate.getMonth()) { case 0: sMonth = "Jan"; break; case 1: sMonth = "Feb"; break; case 2: sMonth = "Mar"; break; case 3: sMonth = "Apr"; break; case 4: sMonth = "May"; break; case 5: sMonth = "Jun"; break; case 6: sMonth = "Jul"; break; case 7: sMonth = "Aug"; break; case 8: sMonth = "Sep"; break; case 9: sMonth = "Oct"; break; case 10: sMonth = "Nov"; break; case 11: sMonth = "Dec"; break; } elCell.innerHTML = sMonth + " " + oDate.getDate() + ", " + oDate.getFullYear(); }; var myColumnDefs = [ { key: "Date", formatter: myFormatDate }, // Uses custom function myFormatDate { key: "Contact", formatter: "email" } // Uses built-in function YAHOO.widget.DataTable.formatEmail ];
// Define a custom format function var myFormatDate = function (elCell, oRecord, oColumn, oData) { var oDate = oData, sMonth; switch(oDate.getMonth()) { case 0: sMonth = "Jan"; break; case 1: sMonth = "Feb"; break; case 2: sMonth = "Mar"; break; case 3: sMonth = "Apr"; break; case 4: sMonth = "May"; break; case 5: sMonth = "Jun"; break; case 6: sMonth = "Jul"; break; case 7: sMonth = "Aug"; break; case 8: sMonth = "Sep"; break; case 9: sMonth = "Oct"; break; case 10: sMonth = "Nov"; break; case 11: sMonth = "Dec"; break; } elCell.innerHTML = sMonth + " " + oDate.getDate() + ", " + oDate.getFullYear(); }; var myColumnDefs = [ { key: "Date", formatter: myFormatDate }, // Uses custom function myFormatDate { key: "Contact", formatter: "email" } // Uses built-in function YAHOO.widget.DataTable.formatEmail ];
If you'd like your DataTable to display nested headers, the control will
automatically correlate the correct set of headers to each <td>
element in order
to support screen reader accessibility. In your Column definitions, any given
Column object literal can itself host an array of Column object literals. Use
the children
property to assign descendant Columns. The
following Column properties will cascade to descendant Columns if they are defined by a
parent but not defined explicitly by children.
className
editor
editorOptions
formatter
resizeable
sortable
width
var myColumnDefs = [ { key: "page", label:"Page URL" }, { key: "Statistics", className: "myClass", children: [ // className will cascade to children { key:"Visits", children: [ { key: "visitsmonth", label: "This Month" }, { key: "visitsytd", label: "YTD", abbr: "Year to Date" } ] }, { key: "Views", children: [ { key: "viewsmonth", label: "This Month" }, { key: "viewsytd", label: "YTD", abbr: "Year to Date" } ] } ]} ];
var myColumnDefs = [ { key: "page", label:"Page URL" }, { key: "Statistics", className: "myClass", children: [ // className will cascade to children { key:"Visits", children: [ { key: "visitsmonth", label: "This Month" }, { key: "visitsytd", label: "YTD", abbr: "Year to Date" } ] }, { key: "Views", children: [ { key: "viewsmonth", label: "This Month" }, { key: "viewsytd", label: "YTD", abbr: "Year to Date" } ] } ]} ];
Please note that not all features are compatible with nested Columns. Specifically, Columns that have children can not be resized, and Columns that are children can neither be hidden/shown nor dragged-and-dropped.
By default, if a Column is defined with sortable:true
, then
clicking on the Column header will execute a basic sort function that supports
comparisons of Strings, Numbers, and Dates.
var myColumnDefs = [ { key: "name", label: "Dog's Name", sortable: true }, { key: "age", label: "Dog's Age", formatter: "number", sortable: true }, { key: "bday", label: "Dog's Birthday", formatter: "date", sortable: true } ];
var myColumnDefs = [ { key: "name", label: "Dog's Name", sortable: true }, { key: "age", label: "Dog's Age", formatter: "number", sortable: true }, { key: "bday", label: "Dog's Birthday", formatter: "date", sortable: true } ];
Keep in mind that sorting a Column first sorts the data in the underlying
RecordSet and then updates the DOM UI to reflect this new sort order. Therefore,
the type of the data (e.g., String, Number, Date, etc.) held in the RecordSet
determines the sort algorithm, not the type as defined in your Column definition
formatter
property.
In general, the RecordSet expects to hold data in native JavaScript types.
For instance, a date is expected to be a JavaScript Date instance, not a
string like "4/26/2005" in order to sort properly. Converting data
types as data comes into your RecordSet is enabled through the parser
property in the fields
array of your DataSource's responseSchema
.
This is especially useful when data is coming over XHR as a String and needs to
be converted to a Number, Boolean, Date, etc. A custom function can be defined,
or you can use one of the static built-in functions:
myDataSource.responseSchema = { fields: [ { key: "name", parser: "string" }, // Stores incoming data as Strings { key: "age", parser: "number" }, // Stores incoming data as Numbers { key: "bday", parser: "date" }, // Stores incoming data as Dates { key: "custom", parser: myParser } // Applies a custom function to incoming data ] };
myDataSource.responseSchema = { fields: [ { key: "name", parser: "string" }, // Stores incoming data as Strings { key: "age", parser: "number" }, // Stores incoming data as Numbers { key: "bday", parser: "date" }, // Stores incoming data as Dates { key: "custom", parser: myParser } // Applies a custom function to incoming data ] };
If your initial data is already sorted, be sure to specify the DataTable config
property sortedBy
to display the proper UI at instantiation. The value
of the property should be either the class constant YAHOO.widget.DataTable.CLASS_ASC
or YAHOO.widget.DataTable.CLASS_DESC
. Now when the user goes to sort this Column,
DataTable will know to sort it in the correct (opposite) direction. Note that
setting the sortedBy
property does not perform a sort on the Column,
it merely applies the appropriate CSS when the DataTable loads.
// The first click on the "receivedDate" Column will sort in descending order var myDataTable = new YAHOO.widget.DataTable("sorted", myColumnDefs, myDataSource, { sortedBy : { key: "receivedDate", dir: YAHOO.widget.DataTable.CLASS_ASC } });
// The first click on the "receivedDate" Column will sort in descending order var myDataTable = new YAHOO.widget.DataTable("sorted", myColumnDefs, myDataSource, { sortedBy : { key: "receivedDate", dir: YAHOO.widget.DataTable.CLASS_ASC } });
The sortOptions
property can be used in your Column definitions
to specify more advanced sort options. If a Column's default sort direction should
be in descending order rather than ascending order, as is often the case for
reverse-chronological date fields, be sure to define the defaultDir
property on sortOptions
:
var myColumnDefs = [ { key: "name", label: "Dog's Name", sortable: true }, { key: "age", label: "Dog's Age", formatter: "number", sortable: true }, { key: "bday", label: "Dog's Birthday", formatter: "date", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC } } // First click sorts latest on top ];
var myColumnDefs = [ { key: "name", label: "Dog's Name", sortable: true }, { key: "age", label: "Dog's Age", formatter: "number", sortable: true }, { key: "bday", label: "Dog's Birthday", formatter: "date", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC } } // First click sorts latest on top ];
Specifying a sortOptions.field
value will point the sort to be executed on the given field.
var myColumnDefs = [ { key: "name", label: "Dog's Name", sortable: true }, { key: "age", label: "Dog's Age", formatter: "number", sortable: true }, { key: "bday_string", label: "Dog's Birthday", sortable: true, sortOptions: { field: "bday_date" } } // Sort occurs on a non-rendered data field ];
var myColumnDefs = [ { key: "name", label: "Dog's Name", sortable: true }, { key: "age", label: "Dog's Age", formatter: "number", sortable: true }, { key: "bday_string", label: "Dog's Birthday", sortable: true, sortOptions: { field: "bday_date" } } // Sort occurs on a non-rendered data field ];
More complex data structures may require custom sort algorithms. You can
provide custom sort functions in your Column definition via the
sortOptions
property. The code below is an example of how to
implement nested sorting, where clicking on Column2's header will sort by values in
Column2 and, if there are equal values, further sort by values in Column1.
Please note that as of the 2.3.0 release, a single sort function is used for both ascending and descending sorts.
// Custom function that defaults to Column1 value if values are equal var mySortFunction = function(a, b, desc, field) { // Deal with empty values if(!YAHOO.lang.isValue(a)) { return (!YAHOO.lang.isValue(b)) ? 0 : 1; } else if(!YAHOO.lang.isValue(b)) { return -1; } // First compare by Column2 var comp = YAHOO.util.Sort.compare; var compState = comp(a.getData(field), b.getData(field), desc); // If values are equal, then compare by Column1 return (compState !== 0) ? compState : comp(a.getData("Column1"), b.getData("Column1"), desc); }; var myColumnDefs = [ { key: "Column1", sortable: true }, // Uses default sort function { key: "Column2", sortable: true, // Uses custom sort function // Provide sortOptions as an object literal sortOptions: { sortFunction: mySortFunction } } ];
// Custom function that defaults to Column1 value if values are equal var mySortFunction = function(a, b, desc, field) { // Deal with empty values if(!YAHOO.lang.isValue(a)) { return (!YAHOO.lang.isValue(b)) ? 0 : 1; } else if(!YAHOO.lang.isValue(b)) { return -1; } // First compare by Column2 var comp = YAHOO.util.Sort.compare; var compState = comp(a.getData(field), b.getData(field), desc); // If values are equal, then compare by Column1 return (compState !== 0) ? compState : comp(a.getData("Column1"), b.getData("Column1"), desc); }; var myColumnDefs = [ { key: "Column1", sortable: true }, // Uses default sort function { key: "Column2", sortable: true, // Uses custom sort function // Provide sortOptions as an object literal sortOptions: { sortFunction: mySortFunction } } ];
Pagination can be used to reduce the real-estate footprint of DataTables with large data sets. As of the 2.5.0 release, implementors should use the new Paginator class to define pagination layout and behavior for the DataTable.
var myConfigs = { paginator : new YAHOO.widget.Paginator({ rowsPerPage: 50 }) }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, myConfigs);
var myConfigs = { paginator : new YAHOO.widget.Paginator({ rowsPerPage: 50 }) }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, myConfigs);
By default, the DataTable will render a set of pagination controls above and below the table:
The Paginator class uses a template and component architecture to afford the greatest flexibility in choosing how to render the pagination controls.
var myConfigs = { paginator : new YAHOO.widget.Paginator({ rowsPerPage: 50, // REQUIRED totalRecords: myData.length, // OPTIONAL // use an existing container element containers: 'my_pagination', // use a custom layout for pagination controls template: "{PageLinks} Show {RowsPerPageDropdown} per page", // show all links pageLinks: YAHOO.widget.Paginator.VALUE_UNLIMITED, // use these in the rows-per-page dropdown rowsPerPageOptions: [25, 50, 100], // use custom page link labels pageLabelBuilder: function (page,paginator) { var recs = paginator.getPageRecords(page); return (recs[0] + 1) + ' - ' + (recs[1] + 1); } }) }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, myConfigs);
var myConfigs = { paginator : new YAHOO.widget.Paginator({ rowsPerPage: 50, // REQUIRED totalRecords: myData.length, // OPTIONAL // use an existing container element containers: 'my_pagination', // use a custom layout for pagination controls template: "{PageLinks} Show {RowsPerPageDropdown} per page", // show all links pageLinks: YAHOO.widget.Paginator.VALUE_UNLIMITED, // use these in the rows-per-page dropdown rowsPerPageOptions: [25, 50, 100], // use custom page link labels pageLabelBuilder: function (page,paginator) { var recs = paginator.getPageRecords(page); return (recs[0] + 1) + ' - ' + (recs[1] + 1); } }) }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, myConfigs);
This Paginator configuration would result in the following UI:
Paginator instances use the configuration attribute template
to describe the markup for rendering the pagination controls. The template string contains placeholders to identify where the various control elements should be located. Each placeholder in the template is the class name of a UI component found in the YAHOO.widget.Paginator.ui
namespace.
The default template is
"{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
.
The following UI components are provided in the 2.5.1 release:
For custom pagination controls, create new UI component classes in the YAHOO.widget.Paginator.ui
namespace and reference them in your Paginator template.
See the API docs for Paginator and each UI component class for available configuration.
Scrolling is another way to conserve the UI footprint of larger data sets. In the DataTable control, scrolling can be
Note: As of the 2.6.0 release, passing scrollable:true
to the DataTable constructor will actually instantiate the subclass ScrollingDataTable. This change means that scrolling cannot be enabled or disabled dynamically at runtime, and implementers who want the scrolling feature must specify it at instantiation, by calling the ScrollingDataTable constructor directly, or alternately either by passing in the config scrollable:true
to the DataTable constructor. APIs that are relevant and necessary only for the scrolling feature have been moved to the ScrollingDataTable subclass and are no longer available from the DataTable class.
Implementers should keep in mind that the scrolling feature inherently entails a performance overhead that may impact user experience. Defining pixel widths for as many Columns as possible, disabling drag-and-drop resizing, and keeping your data size manageable will go a long way towards reducing that overhead.
To enable scrolling, call the YAHOO.widget.ScrollingDataTable constructor and define width and/or height String values. X-scrolling is enabled by only setting a width, y-scrolling is enabled by only setting a height, and xy-scrolling is enabled by setting both. When a height is set, it defines the height of the vertically scrolling body of the table, not including headers.
/* enables x-scrolling */ var myDataTableX = new YAHOO.widget.ScrollingDataTable("myContainer", myColumnDefs, myDataSource, { width: "40em" // width as a string value }); /* enables y-scrolling */ var myDataTableY = new YAHOO.widget.ScrollingDataTable("myContainer", myColumnDefs, myDataSource, { height: "400px" // height as a string value }); /* enables xy-scrolling */ var myDataTableXY = new YAHOO.widget.ScrollingDataTable("myContainer", myColumnDefs, myDataSource, { width: "40em" // width as a string value height: "400px" // height as a string value });
/* enables x-scrolling */ var myDataTableX = new YAHOO.widget.ScrollingDataTable("myContainer", myColumnDefs, myDataSource, { width: "40em" // width as a string value }); /* enables y-scrolling */ var myDataTableY = new YAHOO.widget.ScrollingDataTable("myContainer", myColumnDefs, myDataSource, { height: "400px" // height as a string value }); /* enables xy-scrolling */ var myDataTableXY = new YAHOO.widget.ScrollingDataTable("myContainer", myColumnDefs, myDataSource, { width: "40em" // width as a string value height: "400px" // height as a string value });
In cases where your DataTable needs to display the entirety of a very large set of data, the renderLoopSize
config can help manage browser DOM rendering so that the UI thread does not get locked up on very large tables. Any value greater than 0 will cause the DOM rendering to be executed in setTimeout() chains that render the specified number of rows in each loop. The ideal value should be determined per implementation since there are no hard and fast rules, only general guidelines:
// Render 100 rows per loop var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { renderLoopSize: 100 });
// Render 100 rows per loop var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { renderLoopSize: 100 });
You can enable row selection or cell selection by assigning the built-in
onEventSelectRow
event handler to a Custom Event.
// Enables standard row selection myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
// Enables standard row selection myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
The property selectionMode
is used to enable or disable
modifier keys and define the multi-selection paradigm. By default,
selectionMode
is set to standard
which enables the
modifier keys <shift> and <ctrl> to select multiple rows.
Setting selectionMode
to single
enables row selection
but disables the use of modifier keys for multi-selection.
// Enables single-mode row selection myDataTable.set("selectionMode", "single"); myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
// Enables single-mode row selection myDataTable.set("selectionMode", "single"); myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
Setting selectionMode
to cellblock
,
cellrange
, or singlecell
enables cell selection
in block mode, range mode, or single mode respectively.
// Enables cell-block selection myDataTable.set("selectionMode", "cellblock"); myDataTable.subscribe("cellClickEvent", myDataTable.onEventSelectCell); // Enables cell-range selection myDataTable.set("selectionMode", "cellrange"); myDataTable.subscribe("cellClickEvent", myDataTable.onEventSelectCell); // Enables cell-block selection (modifier keys are disabled) myDataTable.set("selectionMode", "singlecell"); myDataTable.subscribe("cellClickEvent", myDataTable.onEventSelectCell);
// Enables cell-block selection myDataTable.set("selectionMode", "cellblock"); myDataTable.subscribe("cellClickEvent", myDataTable.onEventSelectCell); // Enables cell-range selection myDataTable.set("selectionMode", "cellrange"); myDataTable.subscribe("cellClickEvent", myDataTable.onEventSelectCell); // Enables cell-block selection (modifier keys are disabled) myDataTable.set("selectionMode", "singlecell"); myDataTable.subscribe("cellClickEvent", myDataTable.onEventSelectCell);
Take care that the selectionMode
value matches the mode you have enabled. If
you have assigned the onEventSelectCell
handler, then selectionMode
needs to be set to "cellblock", "cellrange", or "singlecell" exclusively.
Conversely, the values "standard" and "single" are reserved for DataTables with
row selection enabled. Finally, mixing and matching row and cell
selection paradigms is not recommended.
The methods selectRow()
and selectCell()
also
allow you trigger selection programmatically:
// Selects the first row on the page myDataTable.selectRow(myDataTable.getTrEl(0)); // Selects any cell that receives a checkbox click myDataTable.subscribe("checkboxClickEvent", function(oArgs) { var elCheckbox = oArgs.target; if(elCheckbox.checked) { var elCell = this.getTdEl(elCheckbox); this.selectCell(elCell); } });
// Selects the first row on the page myDataTable.selectRow(myDataTable.getTrEl(0)); // Selects any cell that receives a checkbox click myDataTable.subscribe("checkboxClickEvent", function(oArgs) { var elCheckbox = oArgs.target; if(elCheckbox.checked) { var elCell = this.getTdEl(elCheckbox); this.selectCell(elCell); } });
The following methods allow you to retrieve selected rows and cells as an array:
// Returns an array of selected Record IDs (across all pages, if pagination is enabled) myDataTable.getSelectedRows(); // Returns an array of selected TR element references (on current page only, if pagination is enabled) myDataTable.getSelectedTrEls();
// Returns an array of selected Record IDs (across all pages, if pagination is enabled) myDataTable.getSelectedRows(); // Returns an array of selected TR element references (on current page only, if pagination is enabled) myDataTable.getSelectedTrEls();
The look and feel of a selected element can be customized via CSS:
/* white on black */ #myDataTable .yui-dt-selected { background-color: #000; color: #FFF; }
/* white on black */ #myDataTable .yui-dt-selected { background-color: #000; color: #FFF; }
You can enable Column selection by assigning the built-in
onEventSelectColumn
event handler to a Custom Event.
// Enables Column selection myDataTable.subscribe("theadCellDblclickEvent", myDataTable.onEventSelectColumn);
// Enables Column selection myDataTable.subscribe("theadCellDblclickEvent", myDataTable.onEventSelectColumn);
The method selectColumn()
also
allows you trigger selection programmatically:
// Selects the first Column myDataTable.selectColumn(0); // Selects Column when cell is clicked myDataTable.subscribe("cellClickEvent", function (oArgs) { this.selectColumn(this.getColumn(oArgs.target)); });
// Selects the first Column myDataTable.selectColumn(0); // Selects Column when cell is clicked myDataTable.subscribe("cellClickEvent", function (oArgs) { this.selectColumn(this.getColumn(oArgs.target)); });
The following methods allow you to retrieve selected Columns as an array:
// Returns an array of selected Column instances myDataTable.getSelectedColumns();
// Returns an array of selected Column instances myDataTable.getSelectedColumns();
The look and feel of a selected element can be customized via CSS:
/* white on black */ #myDataTable .yui-dt-selected { background-color: #000; color: #FFF; }
/* white on black */ #myDataTable .yui-dt-selected { background-color: #000; color: #FFF; }
You can enable cell, row or Column highlighting by assigning the appropriate built-in event handlers to Custom Events. Please note that mixing and matching cell, row and Column highlighting is not recommended.
// Enables cell highlighting myCellHighlightDataTable.subscribe("cellMouseoverEvent", myCellHighlightDataTable.onEventHighlightCell); myCellHighlightDataTable.subscribe("cellMouseoutEvent", myCellHighlightDataTable.onEventUnhighlightCell); // Enables row highlighting myRowHighlightDataTable.subscribe("rowMouseoverEvent", myRowHighlightDataTable.onEventHighlightRow); myRowHighlightDataTable.subscribe("rowMouseoutEvent", myRowHighlightDataTable.onEventUnhighlightRow); // Enables Column highligting myColHighlightDataTable.subscribe("theadCellMouseoverEvent", myColHighlightDataTable.onEventHighlightColumn); myColHighlightDataTable.subscribe("theadCellMouseoutEvent", myColHighlightDataTable.onEventUnhighlightColumn);
// Enables cell highlighting myCellHighlightDataTable.subscribe("cellMouseoverEvent", myCellHighlightDataTable.onEventHighlightCell); myCellHighlightDataTable.subscribe("cellMouseoutEvent", myCellHighlightDataTable.onEventUnhighlightCell); // Enables row highlighting myRowHighlightDataTable.subscribe("rowMouseoverEvent", myRowHighlightDataTable.onEventHighlightRow); myRowHighlightDataTable.subscribe("rowMouseoutEvent", myRowHighlightDataTable.onEventUnhighlightRow); // Enables Column highligting myColHighlightDataTable.subscribe("theadCellMouseoverEvent", myColHighlightDataTable.onEventHighlightColumn); myColHighlightDataTable.subscribe("theadCellMouseoutEvent", myColHighlightDataTable.onEventUnhighlightColumn);
The look and feel of a highlighted element can be customized via CSS:
/* white on black */ #myDataTable .yui-dt-highlighted { background-color: #000; color: #FFF; }
/* white on black */ #myDataTable .yui-dt-highlighted { background-color: #000; color: #FFF; }
Columns may be hidden, shown, inserted, or deleted. At this time, these APIs are only supported for Columns which are not nested children of other Columns. The methods hideColumn() and showColumn() merely adjust the width values in the UI. However, removeColumn() and insertColumn() will remove and insert Column instances from the actual ColumnSet.
// Get a Column var oColumn = myDataTable.getColumn(3); // Hide Column myDataTable.hideColumn(oColumn); // Show Column myDataTable.showColumn(oColumn); // Remove Column var myRemovedColumn = myDataTable.removeColumn(oColumn); // Insert the removed Column into position 0 myDataTable.insertColumn(myRemovedColumn, 0); // Insert a new Column into position 3 myDataTable.insertColumn({ key: "newCol", label: "New Column" }, 3);
// Get a Column var oColumn = myDataTable.getColumn(3); // Hide Column myDataTable.hideColumn(oColumn); // Show Column myDataTable.showColumn(oColumn); // Remove Column var myRemovedColumn = myDataTable.removeColumn(oColumn); // Insert the removed Column into position 0 myDataTable.insertColumn(myRemovedColumn, 0); // Insert a new Column into position 3 myDataTable.insertColumn({ key: "newCol", label: "New Column" }, 3);
If the Drag & Drop Utility is available on the page, Column reordering can be enabled in your DataTable constructor:
// Enable Drag & Drop reordering var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { draggableColumns: true });
// Enable Drag & Drop reordering var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { draggableColumns: true });
Inline cell editing can be enabled by assigning the built-in onEventShowCellEditor
event handler to a Custom Event. Assign a CellEditor instance to the editor
property in your Column definition:
// Define inline cell editing var myColumnDefs = [ { key: "group", editor: new YAHOO.widget.DropdownCellEditor({ dropdownOptions: [ "one","two","three" ] } )}, { key: "date", editor: new YAHOO.widget.DateCellEditor(), formatter: YAHOO.widget.DataTable.formatDate }, { key: "amount", editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber } ) }, { key: "active", editor: new YAHOO.widget.RadioCellEditor({ radioOptions: [ "yes","no","maybe" ], disableBtns: true } ) }, { key: "colors", editor: new YAHOO.widget.CheckboxCellEditor({ checkboxOptions: [ "red","yellow","blue" ] } ) } ]; myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, this.myDataSource); // Enable inline cell editing myDataTable.subscribe("cellClickEvent", this.myDataTable.onEventShowCellEditor);
// Define inline cell editing var myColumnDefs = [ { key: "group", editor: new YAHOO.widget.DropdownCellEditor({ dropdownOptions: [ "one","two","three" ] } )}, { key: "date", editor: new YAHOO.widget.DateCellEditor(), formatter: YAHOO.widget.DataTable.formatDate }, { key: "amount", editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber } ) }, { key: "active", editor: new YAHOO.widget.RadioCellEditor({ radioOptions: [ "yes","no","maybe" ], disableBtns: true } ) }, { key: "colors", editor: new YAHOO.widget.CheckboxCellEditor({ checkboxOptions: [ "red","yellow","blue" ] } ) } ]; myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, this.myDataSource); // Enable inline cell editing myDataTable.subscribe("cellClickEvent", this.myDataTable.onEventShowCellEditor);
You can pass in configuration options into the CellEditor constructor as an object literal to customize certain behaviors of the editor, such as input validation or default values. Please refer to the API documentation for more information on which properties are supported for each type of CellEditor.
Property | Type | Description |
---|---|---|
asyncSubmitter | Function | Implementer defined function that can submit the input value to a server. This function must accept the arguments fnCallback and oNewValue. When the submission is complete, the function must also call fnCallback(bSuccess, oNewValue) to finish the save routine in the CellEditor. This function can also be used to perform extra validation or input value manipulation. |
defaultValue | Mixed | Default value to use in CellEditor if Record data value is undefined. |
disableBtns | Boolean | True if Save/Cancel buttons should not be displayed in the CellEditor. |
LABEL_CANCEL | String | Text to display on Cancel button. |
LABEL_SAVE | String | Text to display on Save button. |
validator | Function | Validator function for input data returns either the validated (or type-converted) value or undefined. Implementers can use the built-in validator function YAHOO.widget.DataTable.validateNumber or provide their own custom function. |
DataTable provides a built in generateRequest
Attribute, which constructs a string-based request with a default syntax:
"sort={SortColumnKey}&dir={SortColumnDir}&startIndex={PaginationStartIndex}&results={PaginationRowsPerPage}"
The default syntax can be customized by setting a custom function for the generateRequest
Attribute:
var myRequestBuilder = function(oState, oSelf) { // Get states or use defaults oState = oState || { pagination: null, sortedBy: null }; var sort = (oState.sortedBy) ? oState.sortedBy.key : "myDefaultColumnKey"; var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "false" : "true"; var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0; var results = (oState.pagination) ? oState.pagination.rowsPerPage : 100; // Build custom request return "column=" + sort + "&asc=" + true + "&pageStart=" + startIndex + "&pageEnd=" + (startIndex + results - 1); }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { generateRequest: myRequestBuilder });
var myRequestBuilder = function(oState, oSelf) { // Get states or use defaults oState = oState || { pagination: null, sortedBy: null }; var sort = (oState.sortedBy) ? oState.sortedBy.key : "myDefaultColumnKey"; var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "false" : "true"; var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0; var results = (oState.pagination) ? oState.pagination.rowsPerPage : 100; // Build custom request return "column=" + sort + "&asc=" + true + "&pageStart=" + startIndex + "&pageEnd=" + (startIndex + results - 1); }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { generateRequest: myRequestBuilder });
By default, DataTable will fire off a request for data to the DataSource at instantiation. You can disable this feature by setting the config initialLoad
to false
in the constructor:
// Do not load data at instantiation var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { initialLoad: false });
// Do not load data at instantiation var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { initialLoad: false });
If, however, you would like to specify the request sent to the DataSource in the initial load, you can set that value via the initialRequest
config:
// Load 10 orders at instantiation var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { initialRequest: "query=orders&results=10" });
// Load 10 orders at instantiation var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { initialRequest: "query=orders&results=10" });
You can further customize the initial request that is sent to the DataSource by setting the initialLoad
config to be an object literal. Doing so allows you to pass in an arbitrary payload of data that will be accessible to you in the callback loop:
// Load 10 orders at instantiation and pass back the tracking ID var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { initialLoad: { request: "query=orders&results=10", argument: "12345" } }); // Now oPayload is available in the callback loop myDataTable.doBeforeLoadData = function (sRequest, oResponse, oPayload) { // When response returns, oPayload is "12345" // and available in the doBeforeLoadData customizable method return true; };
// Load 10 orders at instantiation and pass back the tracking ID var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, { initialLoad: { request: "query=orders&results=10", argument: "12345" } }); // Now oPayload is available in the callback loop myDataTable.doBeforeLoadData = function (sRequest, oResponse, oPayload) { // When response returns, oPayload is "12345" // and available in the doBeforeLoadData customizable method return true; };
The DataTable provides built-in functions that can be used as callbacks to DataSource's sendRequest
method:
onDataReturnInitializeTable
onDataReturnInsertRows
onDataReturnAppendRows
onDataReturnSetRows
Data can be loaded at runtime with a sendRequest()
call to the DataSource, by passing in a DataTable method as a callback handler.
// Sends a request to the DataSource for more data var oCallback = { success : myDataTable.onDataReturnAppendRows, failure : myDataTable.onDataReturnAppendRows, scope : myDataTable, argument: myDataTable.getState() // data payload that will be returned to the callback function }; this.myDataSource.sendRequest("query=orders&results=10", oCallback);
// Sends a request to the DataSource for more data var oCallback = { success : myDataTable.onDataReturnAppendRows, failure : myDataTable.onDataReturnAppendRows, scope : myDataTable, argument: myDataTable.getState() // data payload that will be returned to the callback function }; this.myDataSource.sendRequest("query=orders&results=10", oCallback);
As a convenience, DataTable has a load()
method that will send the initialRequest
value to the DataSource, and point to the onDataReturnInitializeTable()
built-in callback method . The method accepts a config object that can specify request
, callback
, and datasource
values.
// Sends the "initialRequest" config value to the DataSource for more data // and calls the built-in "onDataReturnInitializeTable()" callback method. myDataTable.load(); // Override all the default values myDataTable.load({ request: "anotherRequest", callback: { success: myDataTable.onDataReturnAppendRows, failure: myDataTable.onDataReturnAppendRows, scope: myDataTable, argument: myDataTable.getState() }, datasource: anotherDataSource });
// Sends the "initialRequest" config value to the DataSource for more data // and calls the built-in "onDataReturnInitializeTable()" callback method. myDataTable.load(); // Override all the default values myDataTable.load({ request: "anotherRequest", callback: { success: myDataTable.onDataReturnAppendRows, failure: myDataTable.onDataReturnAppendRows, scope: myDataTable, argument: myDataTable.getState() }, datasource: anotherDataSource });
The handleDataReturnPayload()
method gives implementers the opportunity to access and manipulate the data payload returned to the callback function. The payload object usually represents DataTable's state values, in order to preserve state across data requests. You can override the function like this:
myDataTable.handleDataReturnPayload = function (oRequest, oResponse, oPayload) { // The payload object usually represents DataTable's state values, including: // oPayload.totalRecords = [number of total records] // oPayload.pagination.rowsPerPage = [number of rows per page] // oPayload.pagination.recordOffset = [index of first record of current page] // oPayload.sortedBy.key = [key of currently sorted column] // oPayload.sortedBy.dir = [direction of currently sorted column] return oPayload; };
myDataTable.handleDataReturnPayload = function (oRequest, oResponse, oPayload) { // The payload object usually represents DataTable's state values, including: // oPayload.totalRecords = [number of total records] // oPayload.pagination.rowsPerPage = [number of rows per page] // oPayload.pagination.recordOffset = [index of first record of current page] // oPayload.sortedBy.key = [key of currently sorted column] // oPayload.sortedBy.dir = [direction of currently sorted column] return oPayload; };
When data is very dynamic in nature, or too large to store locally in JavaScript, sorting and pagination functionality is best implemented on the server side. When dynamicData
is enabled, all pagination and sorting interactions trigger a DataSource request for the new set of data. State management is taken care of for you via an oState object literal which gets sent as a data payload of the sendRequest()
method and then handled in callback function along with the response.
Please note: At this time, row and cell selections are not preserved across dynamicData page views. All selections are purged before requests are sent for new sort or pagination states. Selection preservation for these cases is not provided but should be achieved through custom code.
Often, server-side pagination relies on the server response to know the number of total results. By defining a totalRecords
locator in your DataSource schema's metaFields
, you can access this value to update DataTable's state at runtime before the response data gets loaded by customizing the handleDataReturnPayload()
method.
var myDataSource = new YAHOO.util.XHRDataSource("http://myserver.com?"); myDataSource.responseSchema = { resultsList: "Response.results", fields: [ "name", "type" ], metaFields: { totalRecords: "Response.totalRecords" } // Access server-provided dynamic value }; // Enable sorting for every Column var myColumnDefs = [ { key: "id", sortable: true }, { key: "name", sortable: true }, { key: "description", sortable: true } ]; var myConfigs = { // Set up pagination paginator : new YAHOO.widget.Paginator({ rowsPerPage : 50 }), // Set up initial sort state sortedBy: { key: "id", dir: YAHOO.widget.Datatable.CLASS_ASC }, // Sorting and pagination will be routed to the server via generateRequest dynamicData: true }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, myConfigs); // Update totalRecords on the fly with value from server myDataTable.handleDataReturnPayload = function (oRequest, oResponse, oPayload) { oPayload.totalRecords = oResponse.meta.totalRecords; return oPayload; }
var myDataSource = new YAHOO.util.XHRDataSource("http://myserver.com?"); myDataSource.responseSchema = { resultsList: "Response.results", fields: [ "name", "type" ], metaFields: { totalRecords: "Response.totalRecords" } // Access server-provided dynamic value }; // Enable sorting for every Column var myColumnDefs = [ { key: "id", sortable: true }, { key: "name", sortable: true }, { key: "description", sortable: true } ]; var myConfigs = { // Set up pagination paginator : new YAHOO.widget.Paginator({ rowsPerPage : 50 }), // Set up initial sort state sortedBy: { key: "id", dir: YAHOO.widget.Datatable.CLASS_ASC }, // Sorting and pagination will be routed to the server via generateRequest dynamicData: true }; var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource, myConfigs); // Update totalRecords on the fly with value from server myDataTable.handleDataReturnPayload = function (oRequest, oResponse, oPayload) { oPayload.totalRecords = oResponse.meta.totalRecords; return oPayload; }
When dynamicData
is enabled, sorting or paginating will trigger a DataSource request for new data to reflect the state. By default, the request is formatted with the following syntax:
"sort={SortColumnKey}&dir={SortColumnDir}&startIndex={PaginationStartIndex}&results={PaginationRowsPerPage}"
The request that gets sent for each new state can be easily customized by
defining a custom generateRequest
function (see above).
When providing HTML values to YUI APIs, implementers need to ensure these strings -- especially when containing data from third-party sources or user input data -- have been properly treated so they may safely be inserted into the DOM. The YAHOO.lang.escapeHTML()
method is available for this purpose in version 2.9.0. The built-in "text" formatter (YAHOO.widget.DataTable.formatText) will HTML-escape all string values passed to it before rendering into the DataTable's DOM.
The DataTable control provides a robust Custom Event model to allow you to seamlessly integrate and expand upon its built-in fuctionality. Using Custom Events make it easy to react to user interactions like a cell click or a row click:
myDataTable.subscribe("cellClickEvent", function (oArgs) { var target = oArgs.target, record = this.getRecord(target), column = this.getColumn(target); switch (column.key) { // Do stuff here } });
myDataTable.subscribe("cellClickEvent", function (oArgs) { var target = oArgs.target, record = this.getRecord(target), column = this.getColumn(target); switch (column.key) { // Do stuff here } });
Another example is after you enable inline cell editing (see Inline Cell Editing), you may want to provide a confirmation to your users in reaction to a successful edit event. Note that the newData
value passed to your handler function is the value of the form input field, so in the case of a textbox editor, even if the user has entered a number, the type of the input value will be of type String.
// Create a Custom Event handler var myHandler = function(oArgs) { var oEditor = oArgs.editor, newData = oArgs.newData, oldData = oArgs.oldData; // Output a message to a DIV YAHOO.util.Dom.get("outputDiv").innerHTML = "Cell \"" + oEditor.getTdEl().id + //The edited cell element "\" was successfully updated from \"" + oArgs.oldData + // oArgs.oldData refers to the old value "\" to \"" + oArgs.newData + // oArgs.newData refers to the new value "\" for DataTable \"" + this.toString() + "\"."; // this refers to the DataTable instance }; // Assign the handler to the Custom Event myDataTable.subscribe("editorSaveEvent", myHandler);
// Create a Custom Event handler var myHandler = function(oArgs) { var oEditor = oArgs.editor, newData = oArgs.newData, oldData = oArgs.oldData; // Output a message to a DIV YAHOO.util.Dom.get("outputDiv").innerHTML = "Cell \"" + oEditor.getTdEl().id + //The edited cell element "\" was successfully updated from \"" + oArgs.oldData + // oArgs.oldData refers to the old value "\" to \"" + oArgs.newData + // oArgs.newData refers to the new value "\" for DataTable \"" + this.toString() + "\"."; // this refers to the DataTable instance }; // Assign the handler to the Custom Event myDataTable.subscribe("editorSaveEvent", myHandler);
Please refer to the API documentation for a full list of Custom Events that are available for the DataTable control.
The doBeforeSortColumn()
method gives implementers a hook to update the UI while sorting occurs.
The doBeforeShowCellEditor()
method gives implementers access to the CellEditor instance before it is shown for a edit interaction.
The doBeforeLoadData()
method gives implementers access to the DataSource response before it is consumed by the DataTable instance.
DataTable provides a set of built-in "onEvent" functions that are designed to integrate core functionality with user-driven events. Implementers can assign these functions as handlers to DataTable Custom Events to easily build a rich interactive experience.
// Assign built-in handlers to add functionality myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow); myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow); myDataTable.subscribe("cellClickEvent", myDataTable.onEventShowCellEditor);
// Assign built-in handlers to add functionality myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow); myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow); myDataTable.subscribe("cellClickEvent", myDataTable.onEventShowCellEditor);
DataTable comes with a default presentation or "skin," part of the "Sam Skin" visual treatment that accompanies most YUI controls. You can read more about the general approach to skinning YUI components in this in-depth article.
The CSS provided with DataTable is comprised of core, functional CSS as well as the Sam Skin visual treatment.
To explore the CSS which controls the DataTable's presentation, please review the DataTable Skinning Example where the full CSS for the control is displayed.
Please see the bug repository at YUILibrary.com for a complete list of known issues.
body
ElementWhen draggable Columns are enabled and the "yui-skin-sam" class is not applied to the body
element, the vertical line that indicates the drop target for the Column is not visible. The following custom CSS can be applied as a workaround for implementations that do not wish to apply the "yui-skin-sam" class on the body
element.
.yui-dt-coltarget { width: 5px; background-color: red; }
.yui-dt-coltarget { width: 5px; background-color: red; }
hideColumn()
and showColumn()
on IE<8For DataTables bigger than a certain size, users on IE versions less than 8 may see performance issues when showing or hiding multiple Columns, as described here.
onShow()
after removing display = "none"
on DataTable or ancestor to make sure widths are correctly validated when the widget is unhidden.Gecko browsers may truncate some content of Columns whose widths are not specified if a table's overall content is wider than the viewport or its parent container.
In IE quirks mode, Columns without specified widths are not always auto-sized correctly.
In Opera, table captions interfere with the positioning algorithms needed for Column resizing.
Captions are not supported in ScrollingDataTables.
Opera users may see slow updates when inline cell editing while scrolling is enabled.
In Opera, ScrollingDataTables may experience truncated Column content when widths are not specified in the definition.
Due to a known limitation in Safari, arrow selection of rows and/or cells is not supported at this time.
About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple's Safari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:
There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started as you contemplate how your YUI-based application will render in the mobile world.
More Information:
The core functionality of the DataTable control operates without any major issues on high-end mobile platforms. Implementers should keep in mind the impact that limited real estate may have on end users of the DataTable and be aware of the following preliminary list of smart phone known issues:
The YUI Library and related topics are discussed on the on the YUILibrary.com forums.
Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.
The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.
All YUI 2.x users should review the YUI 2.8.2 security bulletin, which discusses a vulnerability present in YUI 2.4.0-2.8.1.
Copyright © 2013 Yahoo! Inc. All rights reserved.