Construct a grid item from the given element and options
the HTML element tied to this grid after it's been initialized
grid options - public for classes to access, but use methods to modify!
Protected
_add or remove the grid element size event handler
Protected
_return our expected width (or parent) , and optionally of window for dynamic column check
Static
addcall to create a grid with the given options, including loading any children from JSON structure. This will call GridStack.init(), then grid.load() on any passed children (recursively). Great alternative to calling init() if you want entire grid to come from JSON serialized data, including options.
HTML element parent to the grid
grids options used to initialize the grid, and list of children
add a new widget and returns it.
Widget will be always placed even if result height is more than actual grid height.
You need to use willItFit()
before calling addWidget for additional check.
See also makeWidget(el)
for DOM element.
GridStackWidget definition. used MakeWidget(el) if you have dom element instead.
use before calling a bunch of addWidget()
to prevent un-necessary relayouts in between (more efficient)
and get a single event callback. You will see no changes until batchUpdate(false)
is called.
Update current cell height - see GridStackOptions.cellHeight
for format by updating eh Browser CSS variable.
Optional
val: numberOrStringthe cell height. Options:
undefined
: cells content will be made square (match width minus margin)0
: the CSS will be generated by the application insteadthe grid instance for chaining
Gets the current cell width in pixels. This is calculated based on the grid container width divided by the number of columns.
the cell width in pixels
Protected
checkchecks for dynamic column count for our current size, returning true if changed
Set 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] columns,
else you will need to generate correct CSS.
See: https://github.com/gridstack/gridstack.js#change-grid-columns
Integer > 0 (default 12)
specify the type of re-layout that will happen. Options:
column=1
as we always want to vertically stack.the grid instance for chaining
Re-layout grid items to reclaim any empty space. This is useful after removing widgets or when you want to optimize the layout.
layout type. Options:
re-sort items first based on x,y position. Set to false to do your own sorting ahead (default: true)
the grid instance for chaining
Create the default grid item divs and content (possibly lazy loaded) by using GridStack.renderCB().
GridStackNode definition containing widget configuration
the created HTML element with proper grid item structure
Destroys a grid instance. DO NOT CALL any methods or access any vars after this as it will free up members.
if false
grid and items HTML elements will not be removed from the DOM (Optional. Default true
).
Temporarily disables widgets moving/resizing.
If you want a more permanent way (which freezes up resources) use setStatic(true)
instead.
Note: This is a no-op for static grids.
This is a shortcut for:
grid.enableMove(false);
grid.enableResize(false);
if true (default), sub-grids also get updated
the grid instance for chaining
Re-enables widgets moving/resizing - see disable(). Note: This is a no-op for static grids.
This is a shortcut for:
grid.enableMove(true);
grid.enableResize(true);
if true (default), sub-grids also get updated
the grid instance for chaining
Enables/disables widget moving for all widgets. No-op for static grids. Note: locally defined items (with noMove property) still override this setting.
if true widgets will be movable, if false moving is disabled
if true (default), sub-grids also get updated
the grid instance for chaining
Enables/disables widget resizing for all widgets. No-op for static grids. Note: locally defined items (with noResize property) still override this setting.
if true widgets will be resizable, if false resizing is disabled
if true (default), sub-grids also get updated
the grid instance for chaining
Get the position of the cell under a pixel on screen.
the position of the pixel to resolve in absolute coordinates, as an object with top and left properties
if true, value will be based on document position vs parent position (Optional. Default false).
Useful when grid is within position: relative
element
Returns an object with properties x
and y
i.e. the column and row in the grid.
Gets the current cell height in pixels. This takes into account the unit type and converts to pixels if necessary.
if true, forces conversion to pixels even when cellHeight is specified in other units
the cell height in pixels
Static
getGet the global drag & drop implementation instance. This provides access to the underlying drag & drop functionality.
the DDGridStack instance used for drag & drop operations
Returns an array of grid HTML elements (no placeholder) - used to iterate through our children in DOM order. This method excludes placeholder elements and returns only actual grid items.
array of GridItemHTMLElement instances representing all grid items
Returns the current margin value as a number (undefined if the 4 sides don't match). This only returns a number if all sides have the same margin value.
the margin value in pixels, or undefined if sides have different values
Static
initinitializing the HTML element, or selector string, into a grid will return the grid. Calling it again will simply return the existing instance (ignore any passed options). There is also an initAll() version that support multiple grids initialization at once. Or you can use addGrid() to create the entire grid from JSON.
grid options (optional)
element or CSS selector (first one used) to convert to a grid (default to '.grid-stack' class selector)
Static
initWill initialize a list of elements (given a selector) and return an array of grids.
grid options (optional)
elements selector to convert to grids (default to '.grid-stack' class selector)
Checks if the specified rectangular area is empty (no widgets occupy any part of it).
the x coordinate (column) of the area to check
the y coordinate (row) of the area to check
the width in columns of the area to check
the height in rows of the area to check
true if the area is completely empty, false if any widget overlaps
Returns true if change callbacks should be ignored due to column change, sizeToContent, loading, etc. This is useful for callers who want to implement dirty flag functionality.
true if change callbacks are currently being ignored
Load widgets from a list. This will call update() on each (matching by id) or add/remove widgets that are not there.
Used to restore a grid layout for a saved layout list (see save()
).
list of widgets definition to update/create
boolean (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.
the grid instance for chaining
// Basic usage with saved layout
const savedLayout = grid.save(); // Save current layout
// ... later restore it
grid.load(savedLayout);
// Load with custom add/remove callback
grid.load(layout, (items, grid, add) => {
if (add) {
// Custom logic for adding new widgets
items.forEach(item => {
const el = document.createElement('div');
el.innerHTML = item.content || '';
grid.addWidget(el, item);
});
} else {
// Custom logic for removing widgets
items.forEach(item => grid.removeWidget(item.el));
}
});
// Load without adding/removing missing widgets
grid.load(layout, false);
http://gridstackjs.com/demo/serialization.html for complete example
Convert an existing gridItem element into a sub-grid with the given (optional) options, else inherit them from the parent's subGrid options.
gridItem element to convert
Optional
ops: GridStackOptions(optional) sub-grid options, else default to node, then parent settings, else defaults
Optional
nodeToAdd: GridStackNode(optional) node to add to the newly created sub grid (used when dragging over existing regular item)
if true (default) the html inside .grid-stack-content will be saved to child widget
newly created grid
If you add elements to your grid by hand (or have some framework creating DOM), 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.
widget or single selector to convert.
Optional
options: GridStackWidgetwidget definition to use instead of reading attributes or using default sizing values
the converted GridItemHTMLElement
const grid = GridStack.init();
// Create HTML content manually, possibly looking like:
// <div id="item-1" gs-x="0" gs-y="0" gs-w="3" gs-h="2"></div>
grid.el.innerHTML = '<div id="item-1" gs-w="3"></div><div id="item-2"></div>';
// Convert existing elements to widgets
grid.makeWidget('#item-1'); // Uses gs-* attributes from DOM
grid.makeWidget('#item-2', {w: 2, h: 1, content: 'Hello World'});
// Or pass DOM element directly
const element = document.getElementById('item-3');
grid.makeWidget(element, {x: 0, y: 1, w: 4, h: 2});
Updates the margins which will set all 4 sides at once - see GridStackOptions.margin
for format options.
Supports CSS string format of 1, 2, or 4 values or a single number.
margin value - can be:
10
(applies to all sides)'10px 20px'
(top/bottom, left/right)'10px 20px 5px 15px'
(top, right, bottom, left)the grid instance for chaining
Enables/Disables dragging by the user for specific grid elements. For all items and future items, use enableMove() instead. No-op for static grids.
Note: If you want to prevent an item from moving due to being pushed around by another during collision, use the 'locked' property instead.
widget element(s) or selector to modify
if true widget will be draggable, assuming the parent grid isn't noMove or static
the grid instance for chaining
unsubscribe from the 'on' event GridStackEvent
of the event (see possible values) or list of names space separated
Remove all event handlers from the grid. This is useful for cleanup when destroying a grid.
the grid instance for chaining
Register event handler for grid events. You can call this on a single event name, or space separated list.
Supported events:
added
: Called when widgets are being added to a gridchange
: Occurs when widgets change their position/size due to constraints or direct changesdisable
: Called when grid becomes disableddragstart
: Called when grid item starts being draggeddrag
: Called while grid item is being dragged (for each new row/column value)dragstop
: Called after user is done moving the item, with updated DOM attributesdropped
: Called when an item has been dropped and accepted over a gridenable
: Called when grid becomes enabledremoved
: Called when items are being removed from the gridresizestart
: Called before user starts resizing an itemresize
: Called while grid item is being resized (for each new row/column value)resizestop
: Called after user is done resizing the item, with updated DOM attributesevent name(s) to listen for (space separated for multiple)
function to call when event occurs
the grid instance for chaining
Register event handler for grid events. You can call this on a single event name, or space separated list.
Supported events:
added
: Called when widgets are being added to a gridchange
: Occurs when widgets change their position/size due to constraints or direct changesdisable
: Called when grid becomes disableddragstart
: Called when grid item starts being draggeddrag
: Called while grid item is being dragged (for each new row/column value)dragstop
: Called after user is done moving the item, with updated DOM attributesdropped
: Called when an item has been dropped and accepted over a gridenable
: Called when grid becomes enabledremoved
: Called when items are being removed from the gridresizestart
: Called before user starts resizing an itemresize
: Called while grid item is being resized (for each new row/column value)resizestop
: Called after user is done resizing the item, with updated DOM attributesevent name(s) to listen for (space separated for multiple)
function to call when event occurs
the grid instance for chaining
Register event handler for grid events. You can call this on a single event name, or space separated list.
Supported events:
added
: Called when widgets are being added to a gridchange
: Occurs when widgets change their position/size due to constraints or direct changesdisable
: Called when grid becomes disableddragstart
: Called when grid item starts being draggeddrag
: Called while grid item is being dragged (for each new row/column value)dragstop
: Called after user is done moving the item, with updated DOM attributesdropped
: Called when an item has been dropped and accepted over a gridenable
: Called when grid becomes enabledremoved
: Called when items are being removed from the gridresizestart
: Called before user starts resizing an itemresize
: Called while grid item is being resized (for each new row/column value)resizestop
: Called after user is done resizing the item, with updated DOM attributesevent name(s) to listen for (space separated for multiple)
function to call when event occurs
the grid instance for chaining
Register event handler for grid events. You can call this on a single event name, or space separated list.
Supported events:
added
: Called when widgets are being added to a gridchange
: Occurs when widgets change their position/size due to constraints or direct changesdisable
: Called when grid becomes disableddragstart
: Called when grid item starts being draggeddrag
: Called while grid item is being dragged (for each new row/column value)dragstop
: Called after user is done moving the item, with updated DOM attributesdropped
: Called when an item has been dropped and accepted over a gridenable
: Called when grid becomes enabledremoved
: Called when items are being removed from the gridresizestart
: Called before user starts resizing an itemresize
: Called while grid item is being resized (for each new row/column value)resizestop
: Called after user is done resizing the item, with updated DOM attributesevent name(s) to listen for (space separated for multiple)
function to call when event occurs
the grid instance for chaining
Register event handler for grid events. You can call this on a single event name, or space separated list.
Supported events:
added
: Called when widgets are being added to a gridchange
: Occurs when widgets change their position/size due to constraints or direct changesdisable
: Called when grid becomes disableddragstart
: Called when grid item starts being draggeddrag
: Called while grid item is being dragged (for each new row/column value)dragstop
: Called after user is done moving the item, with updated DOM attributesdropped
: Called when an item has been dropped and accepted over a gridenable
: Called when grid becomes enabledremoved
: Called when items are being removed from the gridresizestart
: Called before user starts resizing an itemresize
: Called while grid item is being resized (for each new row/column value)resizestop
: Called after user is done resizing the item, with updated DOM attributesevent name(s) to listen for (space separated for multiple)
function to call when event occurs
the grid instance for chaining
called when we are being resized - check if the one Column Mode needs to be turned on/off
and remember the prev columns we used, or get our count from parent, as well as check for cellHeight==='auto' (square)
or sizeToContent
gridItem options.
prepares the element for drag&drop - this is normally called by makeWidget() unless are are delay loading
GridItemHTMLElement of the widget
Optional
force: boolean = falseStatic
registercall this method to register your engine instead of the default one.
See instead GridStackOptions.engineClass
if you only need to
replace just one instance.
Removes all widgets from the grid.
if false
DOM elements won't be removed from the tree (Default? true
).
if false
(quiet mode) element will not be added to removed list and no 'removed' callbacks will be called (Default? true).
called when an item was converted into a nested grid to accommodate a dragged over item, but then item leaves - return back to the original grid-item. Also called to remove empty sub-grids when last item is dragged out (since re-creating is simple)
Optional
nodeThatRemoved: GridStackNodeRemoves widget from the grid.
if false
DOM element won't be removed from the tree (Default? true).
if false
(quiet mode) element will not be added to removed list and no 'removed' callbacks will be called (Default? true).
Enables/Disables user resizing for specific grid elements. For all items and future items, use enableResize() instead. No-op for static grids.
widget element(s) or selector to modify
if true widget will be resizable, assuming the parent grid isn't noResize or static
the grid instance for chaining
Updates widget height to match the content height to avoid vertical scrollbars or dead space. This automatically adjusts the widget height based on its content size.
Note: This assumes only 1 child under resizeToContentParent='.grid-stack-item-content' (sized to gridItem minus padding) that represents the entire content size.
the grid item element to resize
Rotate widgets by swapping their width and height. This is typically called when the user presses 'r' during dragging. The rotation swaps the w/h dimensions and adjusts min/max constraints accordingly.
widget element(s) or selector to rotate
Optional
relative: Positionoptional pixel coordinate relative to upper/left corner to rotate around (keeps that cell under cursor)
the grid instance for chaining
saves the current layout returning a list of widgets for serialization which might include any nested grids.
if true (default) the latest html inside .grid-stack-content will be saved to GridStackWidget.content field, else it will be removed.
if true (default false), save the grid options itself, so you can call the new GridStack.addGrid() to recreate everything from scratch. GridStackOptions.children would then contain the widget list instead.
callback for each node -> widget, so application can insert additional data to be saved into the widget data structure.
Optional
column: numberif provided, the grid will be saved for the given column size (IFF we have matching internal saved layout, or current layout). Otherwise it will use the largest possible layout (say 12 even if rendering at 1 column) so we can restore to all layouts. NOTE: if you want to save to currently display layout, pass this.getColumn() as column. NOTE2: nested grids will ALWAYS save to the container size to be in sync with parent.
list of widgets or full grid option, including .children list of widgets
Toggle the grid animation state. Toggles the grid-stack-animate
class.
if true the grid will animate.
Optional
delay: booleanif true setting will be set on next event loop.
Toggle the grid static state, which permanently removes/add Drag&Drop support, unlike disable()/enable() that just turns it off/on. Also toggle the grid-stack-static class.
if true the grid become static.
true (default) if css class gets updated
true (default) if sub-grids also get updated
Static
setupcall to setup dragging in from the outside (say toolbar), by specifying the class selection and options. Called during GridStack.init() as options, but can also be called directly (last param are used) in case the toolbar is dynamically create and needs to be set later.
Optional
dragIn: string | HTMLElement[]string selector (ex: '.sidebar-item') or list of dom elements
Optional
dragInOptions: DDDragOptoptions - see DDDragOpt. (default: {handle: '.grid-stack-item-content', appendTo: 'body'}
Optional
widgets: GridStackWidget[]GridStackWidget def to assign to each element which defines what to create on drop
optional root which defaults to document (for shadow dom pass the parent HTMLDocument)
Protected
triggercall given event callback on our main top-most grid (if we're nested)
Updates widget position/size and other info. This is used to change widget properties after creation. Can update position, size, content, and other widget properties.
Note: If you need to call this on all nodes, use load() instead which will update what changed. Setting the same x,y for multiple items will be indeterministic and likely unwanted.
widget element(s) or selector to modify
new widget options (x,y,w,h, etc.). Only those set will be updated.
the grid instance for chaining
Updates the passed in options on the grid (similar to update(widget) for for the grid options).
Returns true if the height of the grid will be less than the vertical constraint. Always returns true if grid doesn't have height constraint.
contains x,y,w,h,auto-position options
Static
Optional
addcallback method use when new items|grids needs to be created or deleted, instead of the default item:
time to wait for animation (if enabled) to be done so content sizing can happen
the HTML element tied to this grid after it's been initialized
engine used to implement non DOM grid functionality
Static
Enginescoping so users can call new GridStack.Engine(12) for example
Protected
Static
enginegrid options - public for classes to access, but use methods to modify!
Optional
parentpoint to a parent grid item if we're nested (inside a grid-item in between 2 Grids)
Static
Optional
rendercallback to create the content of widgets so the app can control how to store and restore it By default this lib will do 'el.textContent = w.content' forcing text only support for avoiding potential XSS issues.
Protected
resizeStatic
Optional
resizecallback to use for resizeToContent instead of the built in one
Static
resizeparent class for sizing content. defaults to '.grid-stack-item-content'
Protected
responseStatic
Optional
savecallback during saving to application can inject extra data for each widget, on top of the grid layout properties
Static
Optional
updatecalled after a widget has been updated (eg: load() into an existing list of children) so application can do extra work
Static
Utilsscoping so users can call GridStack.Utils.sort() for example
Main gridstack class - you will need to call
GridStack.init()
first to initialize your grid. Note: your grid elements MUST have the following classes for the CSS layout to work:Example