Table of Contents generated with DocToc
- Grid Options
- Grid attributes
- Item Options
- Item attributes
- Events
- API
- addWidget(el, [options])
- batchUpdate()
- compact()
- cellHeight(val: number, update = true)
- cellWidth()
- commit()
- column(column, doNotPropagate)
- destroy([removeDOM])
- disable()
- enable()
- enableMove(doEnable, includeNewWidgets)
- enableResize(doEnable, includeNewWidgets)
- float(val?)
- getCellHeight()
- getCellFromPixel(position[, useOffset])
- getGridItems(): GridItemHTMLElement[]
- getMargin()
- isAreaEmpty(x, y, width, height)
- load(layout: GridStackWidget[], boolean | ((w: GridStackWidget, add: boolean) => void) = true)
- locked(el, val)
- makeWidget(el)
- margin(value: numberOrString)
- maxHeight(el, val)
- minHeight(el, val)
- maxWidth(el, val)
- minWidth(el, val)
- movable(el, val)
- move(el, x, y)
- removeWidget(el, removeDOM = true, triggerEvent = true)
- removeAll(removeDOM = true)
- resize(el, width, height)
- resizable(el, val)
- save(): GridStackWidget[]
- setAnimation(doAnimate)
- setStatic(staticValue)
- update(el, x, y, width, height)
- willItFit(x, y, width, height, autoPosition)
- Utils
acceptWidgets- accept widgets dragged from other grids or from outside (default:false). Can be:true(uses'.grid-stack-item'class filter) orfalse- string for explicit class name
function (i: number, element: Element): booleanSee example
alwaysShowResizeHandle- possible values (default:falseonly show on hover)truethe resizing handles are always shown even if the user is not hovering over the widget- advance condition such as this mobile browser agent check:
alwaysShowResizeHandle: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent )See example
animate- turns animation on to smooth transitions (default:true)auto- iffalsegridstack will not initialize existing items (default:true)cellHeight- one cell height (default:auto). Can be:- an integer (px)
- a string (ex: '100px', '10em', '10rem', '10%', `10vh')
- 0 or null, in which case the library will not generate styles for rows. Everything must be defined in CSS files.
'auto'- height will be square cells initially.
column- number of columns (default:12) which can change on the fly withcolumn(N)as well. See exampleddPlugin- class that implement drag'n'drop functionality for gridstack. Iffalsegrid will be static. (default:null- first available plugin will be used)disableDrag- disallows dragging of widgets (default:false).disableOneColumnMode- disables the onColumnMode when the grid width is less than minWidth (default: 'false')disableResize- disallows resizing of widgets (default:false).dragIn- specify the class of items that can be dragged into the grid (ex: dragIn: '.newWidget'dragInOptions- options for items that can be dragged into the grid (ex: dragInOptions: { revert: 'invalid', scroll: false, appendTo: 'body', helper: 'clone' }draggable- allows to override jQuery UI draggable options. (default:{handle: '.grid-stack-item-content', scroll: false, appendTo: 'body', containment: null})dragOutto let user drag nested grid items out of a parent or not (default false) See examplefloat- enable floating widgets (default:false) See examplehandle- draggable handle selector (default:'.grid-stack-item-content')handleClass- draggable handle class (e.g.'grid-stack-item-content'). If sethandleis ignored (default:null)itemClass- widget class (default:'grid-stack-item')margin- gap size around grid item and content (default:10). Can be:- an integer (px)
- a string (ex: '2em', '20px', '2rem')
marginTop: numberOrString - can set individual settings (defaults tomargin)marginRight: numberOrStringmarginBottom: numberOrStringmarginLeft: numberOrStringmaxRow- maximum rows amount. Default is0which means no max.minRow- minimum rows amount which is handy to prevent grid from collapsing when empty. Default is0. You can also do this withmin-heightCSS attribute on the grid div in pixels, which will round to the closest row.minWidth- minimal width. If grid width is less than or equal to, grid will be shown in one-column mode (default:768)oneColumnModeDomSort- set totrueif you want oneColumnMode to use the DOM order and ignore x,y from normal multi column layouts during sorting. This enables you to have custom 1 column layout that differ from the rest. (default?:false)placeholderClass- class for placeholder (default:'grid-stack-placeholder')placeholderText- placeholder default content (default:'')resizable- allows to override jQuery UI resizable options. (default:{autoHide: true, handles: 'se'})removable- iftruewidgets could be removed by dragging outside of the grid. It could also be a jQuery selector string, in this case widgets will be removed by dropping them there (default:false) See exampleremoveTimeout- time in milliseconds before widget is being removed while dragging outside of the grid. (default:2000)row- fix grid number of rows. This is a shortcut of writingminRow:N, maxRow:N. (default0no constrain)rtl- iftrueturns grid to RTL. Possible values aretrue,false,'auto'(default:'auto') See examplestaticGrid- removes drag&drop&resize (defaultfalse). Iftruewidgets are not movable/resizable by the user, but code can still move and oneColumnMode will still work. You don't even need jQueryUI draggable/resizable. A CSS classgrid-stack-staticis also added to the container.styleInHead- iftruewill add style element to<head>otherwise will add it to element's parent node (defaultfalse).
most of the above options are also available as HTML attributes using the data-gs- name prefix with standard dash lower case naming convention (ex: data-gs-column, data-gs-min-row, etc..).
Extras:
data-gs-current-row- (internal) current rows amount. Set by the library only. Can be used by the CSS rules.
options you can pass when calling addWidget()
autoPosition- tells to ignorexandyattributes and to place element to the first available position. Having either one missing will also do that.x,y- (number) element position in column/row. Note: if one is missing this willautoPositionthe itemwidth,height- (number) element size in column/row (default 1x1)maxWidth,minWidth,maxHeight,minHeight- element constraints in column/row (default none)locked- means another widget wouldn't be able to move it during dragging or resizing. The widget can still be dragged or resized by the user. You need to addnoResizeandnoMoveattributes to completely lock the widget.noResize- disable element resizingnoMove- disable element movingresizeHandles- sets resize handles for a specific widget.id- (number | string) good for quick identification (for example in change event)
all item options are also available as HTML attributes using the data-gs- name prefix with standard dash lower case naming convention (ex: data-gs-x, data-gs-min-width, etc..).
Those are events generated by the grid when items are added/removed/changed or drag&drop interaction. In general they pass list of nodes that changed (id, x, y, width, height, etc...) or individual DOM element that is affected.
You can call it on a single event name, or space separated list like:
grid.on('added removed change', ...)
The Typescript GridStackEvent list all possible values, and nothing else is supported by the grid.on() method, though it's possible to register directly for other events generated by the drag&drop plugging implementation detail (currently jquery-ui based so you can still use $(".grid-stack").on(...)).
Called when widgets are being added to a grid
grid.on('added', function(event: Event, items: GridStackNode[]) {
items.forEach(function(item) {...});
});Occurs when widgets change their position/size due to constrain or direct changes
grid.on('change', function(event: Event, items: GridStackNode[]) {
items.forEach(function(item) {...});
});grid.on('disable', function(event: Event) {
let grid: GridStack = event.target.gridstack;
});called when grid item is starting to be dragged
grid.on('dragstart', function(event: Event, el: GridItemHTMLElement) {
});called after the user is done moving the item, with updated DOM attributes.
grid.on('dragstop', function(event: Event, el: GridItemHTMLElement) {
let x = parseInt(el.getAttribute('data-gs-x')) || 0;
// or all values...
let node: GridStackNode = el.gridstackNode; // {x, y, width, height, id, ....}
});called when an item has been dropped and accepted over a grid. If the item came from another grid, the previous widget node info will also be sent (but dom item long gone).
grid.on('dropped', function(event: Event, previousWidget: GridStackNode, newWidget: GridStackNode) {
console.log('Removed widget that was dragged out of grid:', previousWidget);
console.log('Added widget in dropped grid:', newWidget);
});grid.on('enable', function(event: Event) {
let grid: GridStack = event.target.gridstack;
});Called when items are being removed from the grid
grid.on('removed', function(event: Event, items: GridStackNode[]) {
items.forEach(function(item) {...});
});called before the user starts resizing an item
grid.on('resizestart', function(event: Event, el: GridItemHTMLElement) {
});called after the user is done resizing the item, with updated DOM attributes.
grid.on('resizestop', function(event: Event, el: GridItemHTMLElement) {
let width = parseInt(el.getAttribute('data-gs-width')) || 0;
// or all values...
let node: GridStackNode = el.gridstackNode; // {x, y, width, height, id, ....}
});Creates new widget and returns it. Options is an object containing the fields x,y,width,height,etc...
Parameters:
el- html element or string definition to addoptionswidget position/size options (optional) - see GridStackWidget
Widget will be always placed even if result height is more than actual grid height. You need to use willItFit method
before calling addWidget for additional check.
let grid = GridStack.init();
grid.addWidget('<div><div class="grid-stack-item-content">hello</div></div>', {width: 3});starts batch updates. You will see no changes until commit() method is called.
re-layout grid items to reclaim any empty space.
Update current cell height. This method rebuilds an internal CSS stylesheet (unless optional update=false). Note: You can expect performance issues if call this method too often.
grid.cellHeight(grid.cellWidth() * 1.2);Gets current cell width (grid width / # of columns).
Ends batch updates. Updates DOM nodes. You must call it after batchUpdate().
set/get the number of columns in the grid. Will update existing widgets to conform to new number of columns,
as well as cache the original layout so you can revert back to previous positions without loss.
Requires gridstack-extra.css or gridstack-extra.min.css for [2-11],
else you will need to generate correct CSS (see https://github.com/gridstack/gridstack.js#change-grid-columns)
column- Integer > 0 (default 12), if missing it will return the current count instead.doNotPropagate- if true existing widgets will not be updated during a set.
Destroys a grid instance.
Parameters:
removeDOM- iffalsenodes and grid will not be removed from the DOM (Optional. Defaulttrue).
Disables widgets moving/resizing. This is a shortcut for:
grid.enableMove(false);
grid.enableResize(false);Enables widgets moving/resizing. This is a shortcut for:
grid.enableMove(true);
grid.enableResize(true);Enables/disables widget moving. includeNewWidgets will force new widgets to be draggable as per doEnable's value by changing the disableDrag grid option (default: true). This is a shortcut for:
grid.movable('.grid-stack-item', doEnable);
grid.opts.disableDrag = !doEnable;Enables/disables widget resizing. includeNewWidgets will force new widgets to be resizable as per doEnable's value by changing the disableResize grid option (default: true). This is a shortcut for:
grid.resizable('.grid-stack-item', doEnable);
grid.opts.disableResize = !doEnable;set/get floating widgets (default: false)
val- boolean to set true/false, else get the current value
Gets current cell height.
Get the position of the cell under a pixel on screen.
Parameters :
position- the position of the pixel to resolve in absolute coordinates, as an object withtopandleftpropertiesuseOffset- iftrue, value will be based on offset vs position (Optional. Defaultfalse). Useful when grid is withinposition: relativeelement.
Returns an object with properties x and y i.e. the column and row in the grid.
Return list of GridItem HTML dom elements (excluding temporary placeholder)
returns current margin value.
Checks if specified area is empty.
-
load the widgets from a list (see
save()). This will callupdate()on each (matching by id) or add/remove widgets that are not there. -
Optional
addAndRemoveboolean (default true) or callback method can be passed to control if and how missing widgets can be added/removed, giving the user control of insertion. -
used to restore a grid layout for a saved layout list (see
save()). -
addAndRemoveboolean (default true) or callback method can be passed to control if and how missing widgets can be added/removed, giving the user control of insertion. -
see example
Locks/unlocks widget.
el- widget or selector to modify.val- iftruewidget will be locked.
If you add elements to your gridstack container by hand, you have to tell gridstack afterwards to make them widgets. If you want gridstack to add the elements for you, use addWidget instead.
Makes the given element a widget and returns it.
Parameters:
el- element to convert to a widget
let grid = GridStack.init();
grid.el.appendChild('<div id="gsi-1" data-gs-x="0" data-gs-y="0" data-gs-width="3" data-gs-height="2" data-gs-auto-position="true"></div>')
grid.makeWidget('#gsi-1');set the top/right/bottom/left margin between grid item and content. Parameters:
value- new margin value. seecellHeightfor possible value formats. Note: you can instead usemarginTop | marginBottom | marginLeft | marginRightso set the sides separately.
Set the maxHeight for a widget.
el- widget to modify.val- A numeric value of the number of rows
Set the minHeight for a widget.
el- widget to modify.val- A numeric value of the number of rows
Set the maxWidth for a widget.
el- widget to modify.val- A numeric value of the number of columns
Set the minWidth for a widget.
el- widget to modify.val- A numeric value of the number of columns
Enables/Disables moving.
el- widget to modifyval- iftruewidget will be draggable.
Changes widget position
Parameters:
el- widget to movex,y- new position. If value isnullorundefinedit will be ignored.
Removes widget from the grid.
Parameters:
el- widget to remove.removeDOM- iffalsenode won't be removed from the DOM (Optional. Defaulttrue).triggerEventiffalse(quiet mode) element will not be added to removed list and no 'removed' callbacks will be called (Defaulttrue).
Removes all widgets from the grid.
Parameters:
removeDOM- iffalsenodes won't be removed from the DOM (Optional. Defaulttrue).
Changes widget size
Parameters:
el- widget to resizewidth,height- new dimensions. If value isnullorundefinedit will be ignored.
Enables/Disables resizing.
el- widget to modifyval- iftruewidget will be resizable.
- returns the layout of the grid that can be serialized (list of item non default attributes, not just w,y,x,y but also min/max and id). See
load() - see example
Toggle the grid animation state. Toggles the grid-stack-animate class.
doAnimate- iftruethe grid will animate.
Toggle the grid static state. Also toggle the grid-stack-static class.
staticValue- iftruethe grid becomes static.
Parameters:
el- widget to movex,y- new position. If value isnullorundefinedit will be ignored.width,height- new dimensions. If value isnullorundefinedit will be ignored.
Updates widget position/size.
Returns true if the height of the grid will be less the vertical constraint. Always returns true if grid doesn't
have height constraint.
if (grid.willItFit(newNode.x, newNode.y, newNode.width, newNode.height, newNode.autoPosition)) {
grid.addWidget(newNode.el, newNode);
}
else {
alert('Not enough free space to place the widget');
}Sorts array of nodes
nodes- array to sortdir-1for asc,-1for desc (optional)width- width of the grid. Ifundefinedthe width will be calculated automatically (optional).