-
Notifications
You must be signed in to change notification settings - Fork 2k
Slick.Grid
Wiki ▸ API Reference ▸ Slick.Grid
- Constructor
- Core
- Columns
-
Cells
- addCellCssStyles
- canCellBeActive
- canCellBeSelected
- editActiveCell
- getActiveCell
- getCellEditor
- getCellFromEvent
- getCellFromPoint
- getCellNode
- getCellNodeBox
- gotoCell
- navigateDown
- navigateLeft
- navigateNext
- navigatePrev
- navigateRight
- navigateUp
- removeCellCssStyles
- resetActiveCell
- setActiveCell
- setCellCssStyles
- Rendering
- Headers
# Constructor
# var grid = new Slick.Grid(container, data, columns, options);
container
- Container node to create the grid in. This can be a DOM Element, a jQuery node, or a jQuery selector.
data
- Databinding source. This can either be a regular JavaScript array or a custom object exposing getItem(index) and getLength() functions.
columns
- An array of column definition objects. See Column Options for a list of options that can be included on each column definition object.
options
- Additional options. See Grid Options for a list of options that can be included.
Create an instance of the grid.
Example usage, taken from the basic Slickgrid example:
var grid;
var columns = [
{id: "title", name: "Title", field: "title"},
{id: "duration", name: "Duration", field: "duration"},
{id: "%", name: "% Complete", field: "percentComplete"},
{id: "start", name: "Start", field: "start"},
{id: "finish", name: "Finish", field: "finish"},
{id: "effort-driven", name: "Effort Driven", field: "effortDriven"}
];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
$(function () {
var data = [];
for (var i = 0; i < 500; i++) {
data[i] = {
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
}
grid = new Slick.Grid("#myGrid", data, columns, options);
# Core
# grid.init()
Initializes the grid. Called after plugins are registered. Normally, this is called by the constructor, so you don't need to call it. However, in certain cases you may need to delay the initialization until some other process has finished. In that case, set the explicitInitialization
option to true
and call the grid.init()
manually.
# grid.getData()
Returns an array of every data object, unless you're using DataView
in which case it returns a DataView object.
# grid.getDataItem(index)
index
- Item index.
Returns the databinding item at a given position.
// Get the id of the 15th item
var id15 = grid.getDataItem(14).id;
# grid.setData(newData, scrollToTop)
data
- New databinding source. This can either be a regular JavaScript array or a custom object exposinggetItem(index)
andgetLength()
functions.
scrollToTop
- If true, the grid will reset the vertical scroll position to the top of the grid.
Sets a new source for databinding and removes all rendered rows. Note that this doesn't render the new rows - you can follow it with a call to render()
to do that.
# grid.getDataLength()
Returns the size of the databinding source.
// Create an array of just the ids from every data item
var ids = [];
for (var i=0; i<grid.getDataLength() ; i++) {
ids.push(grid.getDataItem(i).id);
}
# grid.getOptions()
Returns an object containing all of the Grid options set on the grid. See a list of Grid Options here.
// Find all elements that are currently selected
var $selectedCells = $('.' + grid.getOptions().selectedCellCssClass);
# grid.getSelectedRows()
Returns an array of row indices corresponding to the currently selected rows.
# grid.getSelectionModel()
Returns the current SelectionModel. See here for more information about SelectionModels.
# grid.setOptions(options)
options
- An object with configuration options.
Extends grid options with a given hash. If there is an active edit, the grid will attempt to commit the changes and only continue if the attempt succeeds.
// set a new CSS class for selected cells
grid.setOptions( { selectedCellCssClass: "newSelection" } );
// Select the first row
grid.setSelectedRows([0]);
// get the elements for the selected cells
$('.newSelection');
# grid.setSelectedRows(rowsArray)
rowsArray
- An array of row numbers.
Accepts an array of row indices and applies the current selectedCellCssClass
to the cells in the row, respecting whether cells have been flagged as selectable
.
// Select the first three rows
grid.setSelectedRows([0, 1, 2]);
# grid.setSelectionModel(selectionModel)
selectionModel
- A SelectionModel.
Unregisters a current selection model and registers a new one. See the definition of SelectionModel for more information.
# Columns
# grid.autosizeColumns()
Proportionately resizes all columns to fill available horizontal space. This does not take the cell contents into consideration.
# grid.getColumnIndex(id)
id
- A column id.
Returns the index of a column with a given id. Since columns can be reordered by the user, this can be used to get the column definition independent of the order:
var column = grid.getColumns()[grid.getColumnIndex("title")]
# grid.getColumns()
Returns an array of column definitions, containing the option settings for each individual column.
// Log to console whether the first column is sortable
var cols = grid.getColumns();
var sortable = cols[0].sortable;
sortable ? console.log("It's sortable!") : console.log("It's not sortable!");
# grid.setColumns(columnDefinitions)
columnDefinitions
- An array of column definitions.
Sets grid columns. Column headers will be recreated and all rendered rows will be removed. To re-render the grid (if necessary), call render()
.
// Change the name of the first column to "First"
var data = grid.getColumns();
data[0].name = "First";
grid.setColumns(data);
# grid.setSortColumn(columnId, ascending)
Accepts a columnId
string and an ascending
boolean. Applies a sort glyph in either ascending or descending form to the header of the column. Note that this does not actually sort the column. It only adds the sort glyph to the header.
# grid.setSortColumns(cols)
Accepts an array of objects in the form [ { columnId: [string], sortAsc: [boolean] }, ... ]
. When called, this will apply a sort glyph in either ascending or descending form to the header of each column specified in the array. Note that this does not actually sort the column. It only adds the sort glyph to the header
# grid.updateColumnHeader(columnId, title, toolTip)
id
- Column id.
title
- New column name.
toolTip
- New column tooltip.
Updates an existing column definition and a corresponding header DOM element with the new title and tooltip.
// Change the column with an id of 'FirstName' to have the name "A First Name", and no tooltip.
grid.updateColumnHeader("FirstName", "A First Name");
# Cells
# grid.addCellCssStyles(key, hash)
key
- A unique key you can use in calls to setCellCssStyles and removeCellCssStyles. If a hash with that key has already been set, an exception will be thrown.
hash
- A hash of additional cell CSS classes keyed by row number and then by column id. Multiple CSS classes can be specified and separated by space.Example:
{ 0: { "number_column": "cell-bold", "title_column": "cell-title cell-highlighted" }, 4: { "percent_column": "cell-highlighted" } }
Adds an "overlay" of CSS classes to cell DOM elements. SlickGrid can have many such overlays associated with different keys and they are frequently used by plugins. For example, SlickGrid uses this method internally to decorate selected cells with selectedCellCssClass (see options).
# grid.canCellBeActive(row, col)
row
- A row index.
col
- A column index.
Returns true
if you can click on a given cell and make it the active focus.
# grid.canCellBeSelected(row, col)
row
- A row index.
col
- A column index.
Returns true
if selecting the row causes this particular cell to have the selectedCellCssClass
applied to it. A cell can be selected if it exists and if it isn't on an empty / "Add New" row and if it is not marked as "unselectable" in the column definition.
# grid.editActiveCell(editor)
editor
- A SlickGrid editor (see examples inslick.editors.js
).
Attempts to switch the active cell into edit mode. Will throw an error if the cell is set to be not editable. Uses the specified editor
, otherwise defaults to any default editor for that given cell.
// Assuming slick.editors.js is included...
// Set the first cell in the first row to be active
grid.setActiveCell(0,0);
// Invoke the Date editor on that cell
grid.editActiveCell(Slick.Editors.Date);
# grid.flashCell(row, cell, speed)
row
- A row index.
cell
- A column index.
speed
(optional) - The milliseconds delay between the toggling calls. Defaults to 100 ms.
Flashes the cell twice by toggling the CSS class 4 times.
# grid.getActiveCell()
Returns an object representing the coordinates of the currently active cell:
{
row: activeRow,
cell: activeCell
}
# grid.getActiveCellNode()
Returns the DOM element containing the currently active cell. If no cell is active, null is returned.
// Get the element for the active cell
var $active = $(grid.getActiveCellNode())
// Add a new class to the active cell
$active.addClass('myClass');
# grid.getActiveCellPosition()
Returns an object representing information about the active cell's position. All coordinates are absolute and take into consideration the visibility and scrolling position of all ancestors. The object takes the form:
{
bottom: [numPixels],
height: [numPixels],
left: [numPixels],
right: [numPixels],
top: [numPixels],
visible: [boolean],
width: [numPixels]
}
# grid.getCellCssStyles(key)
key
- A string.
Accepts a key name, returns the group of CSS styles defined under that name. See setCellCssStyles
for more info.
# grid.getCellEditor()
Returns the active cell editor. If there is no actively edited cell, null is returned.
# grid.getCellFromEvent(e)
e
- A standard W3C/jQuery event.
Returns a hash containing row and cell indexes from a standard W3C/jQuery event.
# grid.getCellFromPoint(x, y)
x
- An x coordinate.
y
- A y coordinate.
Returns a hash containing row and cell indexes. Coordinates are relative to the top left corner of the grid beginning with the first row (not including the column headers).
# grid.getCellNode(row, cell)
row
- A row index.
cell
- A column index.
Returns a DOM element containing a cell at a given row and cell.
# grid.getCellNodeBox(row, cell)
row
- A row index.
cell
- A column index.
Returns an object representing information about a cell's position. All coordinates are absolute and take into consideration the visibility and scrolling position of all ancestors. The object takes the form:
{
bottom: [numPixels],
height: [numPixels],
left: [numPixels],
right: [numPixels],
top: [numPixels],
visible: [boolean],
width: [numPixels]
}
# grid.gotoCell(row, cell, forceEdit)
Accepts a row
integer and a cell
integer, scrolling the view to the row where row
is its row index, and cell
is its cell index. Optionally accepts a forceEdit
boolean which, if true, will attempt to initiate the edit dialogue for the field in the specified cell.
Unlike setActiveCell
, this scrolls the row into the viewport and sets the keyboard focus.
# grid.navigateDown()
Switches the active cell one row down skipping unselectable cells. Returns a boolean saying whether it was able to complete or not.
# grid.navigateLeft()
Switches the active cell one cell left skipping unselectable cells. Unline navigatePrev
, navigateLeft
stops at the first cell of the row. Returns a boolean saying whether it was able to complete or not.
# grid.navigateNext()
Tabs over active cell to the next selectable cell. Returns a boolean saying whether it was able to complete or not.
# grid.navigatePrev()
Tabs over active cell to the previous selectable cell. Returns a boolean saying whether it was able to complete or not.
# grid.navigateRight()
Switches the active cell one cell right skipping unselectable cells. Unline navigateNext
, navigateRight
stops at the last cell of the row. Returns a boolean saying whether it was able to complete or not.
# grid.navigateUp()
Switches the active cell one row up skipping unselectable cells. Returns a boolean saying whether it was able to complete or not.
# grid.removeCellCssStyles(key)
key
- A string key.
Removes an "overlay" of CSS classes from cell DOM elements. See setCellCssStyles
for more.
# grid.resetActiveCell()
Resets active cell.
# grid.setActiveCell(row, cell)
row
- A row index.
cell
- A column index.
Sets an active cell.
# grid.setCellCssStyles(key, hash)
key
- A string key. Will overwrite any data already associated with this key.
hash
- A hash of additional cell CSS classes keyed by row number and then by column id. Multiple CSS classes can be specified and separated by space.Example:
{ 0: { "number_column": "cell-bold", "title_column": "cell-title cell-highlighted" }, 4: { "percent_column": "cell-highlighted" } }
Sets CSS classes to specific grid cells by calling removeCellCssStyles(key)
followed by addCellCssStyles(key, hash)
. key
is name for this set of styles so you can reference it later - to modify it or remove it, for example. hash
is a per-row-index, per-column-name nested hash of CSS classes to apply.
Suppose you have a grid with columns:
["login", "name", "birthday", "age", "likes_icecream", "favorite_cake"]
...and you'd like to highlight the "birthday" and "age" columns for people whose birthday is today, in this case, rows at index 0 and 9. (The first and tenth row in the grid).
.highlight{ background: yellow }
grid.setCellCssStyles("birthday_highlight", {
0: {
birthday: "highlight",
age: "highlight"
},
9: {
birthday: "highlight",
age: "highlight"
}
})
# Rendering
# grid.getCanvasNode()
Returns the DIV element matching class grid-canvas
, which contains every data row currently being rendered in the DOM.
// Get the total number of data rows being rendered in the DOM.
var numRenderedRows = $(grid.getCanvasNode()).children().length;
# grid.getGridPosition()
Returns an object representing information about the grid's position on the page. The object takes the form:
{
bottom: [numPixels],
height: [numPixels],
left: [numPixels],
right: [numPixels],
top: [numPixels],
visible: [boolean],
width: [numPixels]
}
# grid.getRenderedRange(viewportTop, viewportLeft)
viewportTop
(optional) - The number of pixels offset from the top of the grid.
viewportLeft
(optional) - The number of pixels offset from the left of the grid.
If passed no arguments, returns an object that tells you the range of rows (by row number) currently being rendered, as well as the left/right range of pixels currently rendered. { top: [rowIndex], bottom: [rowIndex], leftPx: [numPixels], rightPx: [numPixels] }
The options viewportTop
and viewportLeft
are optional, and tell what what would be rendered at a certain scroll top/left offset. For example, grid.getRenderedRange(1000)
would essentially be asking: "if I were to scroll 1000 pixels down, what rows would be rendered?"
# grid.getViewport(viewportTop, viewportLeft)
viewportTop
(optional) - The number of pixels offset from the top of the grid.
viewportLeft
(optional) - The number of pixels offset from the left of the grid.
Returns an object telling you which rows are currently being displayed on the screen, and also the pixel offsets for left/right scrolling. { top: [rowIndex], bottom: [rowIndex], leftPx: [numPixels], rightPx: [numPixels] }
Also accepts viewportTop
and viewportLeft
offsets to tell you what would be shown to the user if you were to scroll to that point.
# grid.invalidate()
Redraws the grid. Invalidates all rows and calls render()
.
// Change the name property of the first row
var data = grid.getData();
data[0].name = "New name!"
// Call invalidate to render the data again. No need to call render, as this calls it for you.
grid.invalidate();
# grid.invalidateAllRows()
Tells the grid that all rows in the table are invalid. (If render()
is called after this, it will redraw the entire grid.)
# grid.invalidateRow(row)
row
- A row index.
Tells the grid that the row specified by row
is invalid. (If render()
is called after this, it will redraw the contents of that row.)
# grid.invalidateRows(rows)
rows
- An array of row indices.
Accepts an array of row indices, and tells the grid that those rows are invalid. (If render()
is called after this, it will redraw the contents of those rows.)
// Change the name property of the first row
var data = grid.getData();
data[0].name = "New name!"
data[1].name = "Another new name!"
// Call invalidateRows to invalidate the first two rows
grid.invalidateRows([0,1]);
// Call render to render them again
grid.render();
# grid.render()
Rerenders rows in the DOM.
# grid.resizeCanvas()
Resizes the canvas to fit the current DIV container. (For example, to resize the grid, you would first change the size of the div, then call resizeCanvas()
.)
# grid.scrollCellIntoView(row, cell)
row
- A row index.
cell
- A column index.
Scrolls the indicated cell into view.
Note that this does nothing unless the indicated column is already not in view. For example, if the grid is scrolled to the far left and you were looking at row 0, calling scrollCellIntoView(100,0)
would not simply scroll you to row 100. But if column 8 were out of view and you called scrollCellIntoView(100,8)
, then it would scroll down and to the right.
# grid.scrollRowIntoView(row, doPaging)
row
- A row index.
doPaging
- A boolean. Iffalse
, the grid will scroll so the indicated row is at the top of the view. Iftrue
, the grid will scroll so the indicated row is at the bottom of the view. Defaults tofalse
.
Scrolls the view to the indicated row.
# grid.scrollRowToTop(row)
row
- A row index.
Scrolls the view to the indicated row, placing the row at the top of the view.
# grid.updateCell(row, cell)
TODO
// put stuff here
# grid.updateRow(row)
TODO
// put stuff here
# grid.updateRowCount()
TODO
// put stuff here
# Headers
# grid.getHeaderRow()
Returns the element of a DIV row beneath the actual column headers. For an example of how you might use this, see the header row quick filter example, which grabs the element, appends inputs, and delegates events to the inputs.
# grid.getHeaderRowColumn(columnId)
columnId
- Theid
string of a column.
If a header row is implemented and has one child for each column, as seen in the header row quick filter example, you may use this function to pass a columnId and get the individual cell from that header row. Returns a DIV element.
# grid.getSortColumns()
Returns an array of objects representing columns that have a sort glyph in the header:
{
columnId: [string],
sortAsc: [boolean]
}
# grid.getTopPanel()
Returns the DIV element of the top panel. The panel is hidden by default, but you can show it by initializing the grid with showTopPanel
set to true
, or by calling grid.setTopPanelVisibility(true)
.
// Create a subheader and attach it to the top panel
$("<div>Here is a subheader!</div>")
.appendTo(grid.getTopPanel());
// Show the top panel
grid.setTopPanelVisibility(true);
# grid.setHeaderRowVisibility(visible)
Note:
Earlier Versions used grid.showTopPanel()
and grid.hideTopPanel()
these have now been replaced with grid.setTopPanelVisibility(true)
and grid.setTopPanelVisibility(false);
TODO
// put stuff here
Resources
- API Reference
- Grid
- Grid Options
- Column Options
- Grid Events
- DataView
- Examples
- Providing data to the grid
- Plugins & Third-party packages
Learning
Tests
Contact/Support