UNPKG

gridstack

Version:

TypeScript/JS lib for dashboard layout and creation, responsive, mobile support, no external dependencies, with many wrappers (React, Angular, Vue, Ember, knockout...)

1,757 lines (1,182 loc) 194 kB
# gridstack v12.3.3 ## Classes ## Table of Contents - [GridStack](#gridstack) - [GridStackEngine](#gridstackengine) - [Utils](#utils) - [GridStackOptions](#gridstackoptions) - [`abstract` DDBaseImplement](#abstract-ddbaseimplement) - [DDDraggable](#dddraggable) - [DDDroppable](#dddroppable) - [DDElement](#ddelement) - [DDGridStack](#ddgridstack) - [DDManager](#ddmanager) - [DDResizable](#ddresizable-1) - [DDResizableHandle](#ddresizablehandle) - [Breakpoint](#breakpoint) - [CellPosition](#cellposition) - [DDDragOpt](#dddragopt) - [DDDroppableOpt](#dddroppableopt) - [DDElementHost](#ddelementhost) - [DDRemoveOpt](#ddremoveopt) - [DDResizableHandleOpt](#ddresizablehandleopt) - [DDResizableOpt](#ddresizableopt) - [DDResizeOpt](#ddresizeopt) - [DDUIData](#dduidata) - [DragTransform](#dragtransform) - [GridHTMLElement](#gridhtmlelement) - [GridItemHTMLElement](#griditemhtmlelement) - [GridStackEngineOptions](#gridstackengineoptions) - [GridStackMoveOpts](#gridstackmoveopts) - [GridStackNode](#gridstacknode-2) - [GridStackPosition](#gridstackposition) - [GridStackWidget](#gridstackwidget) - [HeightData](#heightdata) - [HTMLElementExtendOpt\<T\>](#htmlelementextendoptt) - [MousePosition](#mouseposition) - [Position](#position-1) - [Rect](#rect-1) - [Responsive](#responsive) - [Size](#size-1) - [gridDefaults](#griddefaults) - [AddRemoveFcn()](#addremovefcn) - [ColumnOptions](#columnoptions) - [CompactOptions](#compactoptions) - [DDCallback()](#ddcallback) - [DDDropOpt](#dddropopt) - [DDKey](#ddkey) - [DDOpts](#ddopts) - [DDValue](#ddvalue) - [EventCallback()](#eventcallback) - [GridStackDroppedHandler()](#gridstackdroppedhandler) - [GridStackElement](#gridstackelement) - [GridStackElementHandler()](#gridstackelementhandler) - [GridStackEvent](#gridstackevent) - [GridStackEventHandler()](#gridstackeventhandler) - [GridStackEventHandlerCallback](#gridstackeventhandlercallback) - [GridStackNodesHandler()](#gridstacknodeshandler) - [numberOrString](#numberorstring) - [RenderFcn()](#renderfcn) - [ResizeToContentFcn()](#resizetocontentfcn) - [SaveFcn()](#savefcn) <a id="gridstack"></a> ### GridStack Defined in: [gridstack.ts:76](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L76) 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 ```ts <div class="grid-stack"> <div class="grid-stack-item"> <div class="grid-stack-item-content">Item 1</div> </div> </div> ``` #### Constructors ##### Constructor ```ts new GridStack(el, opts): GridStack; ``` Defined in: [gridstack.ts:266](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L266) Construct a grid item from the given element and options ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `el` | [`GridHTMLElement`](#gridhtmlelement) | the HTML element tied to this grid after it's been initialized | | `opts` | [`GridStackOptions`](#gridstackoptions) | grid options - public for classes to access, but use methods to modify! | ###### Returns [`GridStack`](#gridstack-1) #### Methods ##### \_updateResizeEvent() ```ts protected _updateResizeEvent(forceRemove): GridStack; ``` Defined in: [gridstack.ts:2091](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2091) add or remove the grid element size event handler ###### Parameters | Parameter | Type | Default value | | ------ | ------ | ------ | | `forceRemove` | `boolean` | `false` | ###### Returns [`GridStack`](#gridstack-1) ##### \_widthOrContainer() ```ts protected _widthOrContainer(forBreakpoint): number; ``` Defined in: [gridstack.ts:954](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L954) return our expected width (or parent) , and optionally of window for dynamic column check ###### Parameters | Parameter | Type | Default value | | ------ | ------ | ------ | | `forBreakpoint` | `boolean` | `false` | ###### Returns `number` ##### addGrid() ```ts static addGrid(parent, opt): GridStack; ``` Defined in: [gridstack.ts:141](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L141) call 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. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `parent` | `HTMLElement` | HTML element parent to the grid | | `opt` | [`GridStackOptions`](#gridstackoptions) | grids options used to initialize the grid, and list of children | ###### Returns [`GridStack`](#gridstack-1) ##### addWidget() ```ts addWidget(w): GridItemHTMLElement; ``` Defined in: [gridstack.ts:432](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L432) 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. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `w` | [`GridStackWidget`](#gridstackwidget) | GridStackWidget definition. used MakeWidget(el) if you have dom element instead. | ###### Returns [`GridItemHTMLElement`](#griditemhtmlelement) ###### Example ```ts const grid = GridStack.init(); grid.addWidget({w: 3, content: 'hello'}); ``` ##### batchUpdate() ```ts batchUpdate(flag): GridStack; ``` Defined in: [gridstack.ts:833](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L833) 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. ###### Parameters | Parameter | Type | Default value | | ------ | ------ | ------ | | `flag` | `boolean` | `true` | ###### Returns [`GridStack`](#gridstack-1) ##### cellHeight() ```ts cellHeight(val?): GridStack; ``` Defined in: [gridstack.ts:904](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L904) Update current cell height - see `GridStackOptions.cellHeight` for format by updating eh Browser CSS variable. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `val?` | [`numberOrString`](#numberorstring) | the cell height. Options: - `undefined`: cells content will be made square (match width minus margin) - `0`: the CSS will be generated by the application instead - number: height in pixels - string: height with units (e.g., '70px', '5rem', '2em') | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts grid.cellHeight(100); // 100px height grid.cellHeight('70px'); // explicit pixel height grid.cellHeight('5rem'); // relative to root font size grid.cellHeight(grid.cellWidth() * 1.2); // aspect ratio grid.cellHeight('auto'); // auto-size based on content ``` ##### cellWidth() ```ts cellWidth(): number; ``` Defined in: [gridstack.ts:950](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L950) Gets the current cell width in pixels. This is calculated based on the grid container width divided by the number of columns. ###### Returns `number` the cell width in pixels ###### Example ```ts const width = grid.cellWidth(); console.log('Cell width:', width, 'px'); // Use cell width to calculate widget dimensions const widgetWidth = width * 3; // For a 3-column wide widget ``` ##### checkDynamicColumn() ```ts protected checkDynamicColumn(): boolean; ``` Defined in: [gridstack.ts:960](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L960) checks for dynamic column count for our current size, returning true if changed ###### Returns `boolean` ##### column() ```ts column(column, layout): GridStack; ``` Defined in: [gridstack.ts:1039](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1039) 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 ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `column` | `number` | `undefined` | Integer > 0 (default 12) | | `layout` | [`ColumnOptions`](#columnoptions) | `'moveScale'` | specify the type of re-layout that will happen. Options: - 'moveScale' (default): scale widget positions and sizes - 'move': keep widget sizes, only move positions - 'scale': keep widget positions, only scale sizes - 'none': don't change widget positions or sizes Note: items will never be outside of the current column boundaries. Ignored for `column=1` as we always want to vertically stack. | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Change to 6 columns with default scaling grid.column(6); // Change to 4 columns, only move positions grid.column(4, 'move'); // Single column layout (vertical stack) grid.column(1); ``` ##### commit() ```ts commit(): GridStack; ``` Defined in: [gridstack.ts:3020](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L3020) ###### Returns [`GridStack`](#gridstack-1) ##### compact() ```ts compact(layout, doSort): GridStack; ``` Defined in: [gridstack.ts:1005](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1005) Re-layout grid items to reclaim any empty space. This is useful after removing widgets or when you want to optimize the layout. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `layout` | [`CompactOptions`](#compactoptions) | `'compact'` | layout type. Options: - 'compact' (default): might re-order items to fill any empty space - 'list': keep the widget left->right order the same, even if that means leaving an empty slot if things don't fit | | `doSort` | `boolean` | `true` | re-sort items first based on x,y position. Set to false to do your own sorting ahead (default: true) | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Compact layout after removing widgets grid.removeWidget('.widget-to-remove'); grid.compact(); // Use list layout (preserve order) grid.compact('list'); // Compact without sorting first grid.compact('compact', false); ``` ##### createWidgetDivs() ```ts createWidgetDivs(n): HTMLElement; ``` Defined in: [gridstack.ts:478](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L478) Create the default grid item divs and content (possibly lazy loaded) by using GridStack.renderCB(). ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `n` | [`GridStackNode`](#gridstacknode-2) | GridStackNode definition containing widget configuration | ###### Returns `HTMLElement` the created HTML element with proper grid item structure ###### Example ```ts const element = grid.createWidgetDivs({ w: 2, h: 1, content: 'Hello World' }); ``` ##### destroy() ```ts destroy(removeDOM): GridStack; ``` Defined in: [gridstack.ts:1113](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1113) Destroys a grid instance. DO NOT CALL any methods or access any vars after this as it will free up members. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `removeDOM` | `boolean` | `true` | if `false` grid and items HTML elements will not be removed from the DOM (Optional. Default `true`). | ###### Returns [`GridStack`](#gridstack-1) ##### disable() ```ts disable(recurse): GridStack; ``` Defined in: [gridstack.ts:2292](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2292) 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: ```typescript grid.enableMove(false); grid.enableResize(false); ``` ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `recurse` | `boolean` | `true` | if true (default), sub-grids also get updated | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Disable all interactions grid.disable(); // Disable only this grid, not sub-grids grid.disable(false); ``` ##### enable() ```ts enable(recurse): GridStack; ``` Defined in: [gridstack.ts:2319](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2319) Re-enables widgets moving/resizing - see disable(). Note: This is a no-op for static grids. This is a shortcut for: ```typescript grid.enableMove(true); grid.enableResize(true); ``` ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `recurse` | `boolean` | `true` | if true (default), sub-grids also get updated | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Re-enable all interactions grid.enable(); // Enable only this grid, not sub-grids grid.enable(false); ``` ##### enableMove() ```ts enableMove(doEnable, recurse): GridStack; ``` Defined in: [gridstack.ts:2345](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2345) Enables/disables widget moving for all widgets. No-op for static grids. Note: locally defined items (with noMove property) still override this setting. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `doEnable` | `boolean` | `undefined` | if true widgets will be movable, if false moving is disabled | | `recurse` | `boolean` | `true` | if true (default), sub-grids also get updated | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Enable moving for all widgets grid.enableMove(true); // Disable moving for all widgets grid.enableMove(false); // Enable only this grid, not sub-grids grid.enableMove(true, false); ``` ##### enableResize() ```ts enableResize(doEnable, recurse): GridStack; ``` Defined in: [gridstack.ts:2373](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2373) Enables/disables widget resizing for all widgets. No-op for static grids. Note: locally defined items (with noResize property) still override this setting. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `doEnable` | `boolean` | `undefined` | if true widgets will be resizable, if false resizing is disabled | | `recurse` | `boolean` | `true` | if true (default), sub-grids also get updated | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Enable resizing for all widgets grid.enableResize(true); // Disable resizing for all widgets grid.enableResize(false); // Enable only this grid, not sub-grids grid.enableResize(true, false); ``` ##### float() ```ts float(val): GridStack; ``` Defined in: [gridstack.ts:1147](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1147) Enable/disable floating widgets (default: `false`). When enabled, widgets can float up to fill empty spaces. See [example](http://gridstackjs.com/demo/float.html) ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `val` | `boolean` | true to enable floating, false to disable | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts grid.float(true); // Enable floating grid.float(false); // Disable floating (default) ``` ##### getCellFromPixel() ```ts getCellFromPixel(position, useDocRelative): CellPosition; ``` Defined in: [gridstack.ts:1177](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1177) Get the position of the cell under a pixel on screen. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `position` | [`MousePosition`](#mouseposition) | `undefined` | the position of the pixel to resolve in absolute coordinates, as an object with top and left properties | | `useDocRelative` | `boolean` | `false` | 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. | ###### Returns [`CellPosition`](#cellposition) ##### getCellHeight() ```ts getCellHeight(forcePixel): number; ``` Defined in: [gridstack.ts:857](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L857) Gets the current cell height in pixels. This takes into account the unit type and converts to pixels if necessary. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `forcePixel` | `boolean` | `false` | if true, forces conversion to pixels even when cellHeight is specified in other units | ###### Returns `number` the cell height in pixels ###### Example ```ts const height = grid.getCellHeight(); console.log('Cell height:', height, 'px'); // Force pixel conversion const pixelHeight = grid.getCellHeight(true); ``` ##### getColumn() ```ts getColumn(): number; ``` Defined in: [gridstack.ts:1076](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1076) Get the number of columns in the grid (default 12). ###### Returns `number` the current number of columns in the grid ###### Example ```ts const columnCount = grid.getColumn(); // returns 12 by default ``` ##### getDD() ```ts static getDD(): DDGridStack; ``` Defined in: [gridstack.ts:2189](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2189) Get the global drag & drop implementation instance. This provides access to the underlying drag & drop functionality. ###### Returns [`DDGridStack`](#ddgridstack) the DDGridStack instance used for drag & drop operations ###### Example ```ts const dd = GridStack.getDD(); // Access drag & drop functionality ``` ##### getFloat() ```ts getFloat(): boolean; ``` Defined in: [gridstack.ts:1164](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1164) Get the current float mode setting. ###### Returns `boolean` true if floating is enabled, false otherwise ###### Example ```ts const isFloating = grid.getFloat(); console.log('Floating enabled:', isFloating); ``` ##### getGridItems() ```ts getGridItems(): GridItemHTMLElement[]; ``` Defined in: [gridstack.ts:1090](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1090) 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. ###### Returns [`GridItemHTMLElement`](#griditemhtmlelement)[] array of GridItemHTMLElement instances representing all grid items ###### Example ```ts const items = grid.getGridItems(); items.forEach(item => { console.log('Item ID:', item.gridstackNode.id); }); ``` ##### getMargin() ```ts getMargin(): number; ``` Defined in: [gridstack.ts:1788](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1788) 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. ###### Returns `number` the margin value in pixels, or undefined if sides have different values ###### Example ```ts const margin = grid.getMargin(); if (margin !== undefined) { console.log('Uniform margin:', margin, 'px'); } else { console.log('Margins are different on different sides'); } ``` ##### getRow() ```ts getRow(): number; ``` Defined in: [gridstack.ts:1207](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1207) Returns the current number of rows, which will be at least `minRow` if set. The row count is based on the highest positioned widget in the grid. ###### Returns `number` the current number of rows in the grid ###### Example ```ts const rowCount = grid.getRow(); console.log('Grid has', rowCount, 'rows'); ``` ##### init() ```ts static init(options, elOrString): GridStack; ``` Defined in: [gridstack.ts:91](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L91) initializing 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. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `options` | [`GridStackOptions`](#gridstackoptions) | `{}` | grid options (optional) | | `elOrString` | [`GridStackElement`](#gridstackelement) | `'.grid-stack'` | element or CSS selector (first one used) to convert to a grid (default to '.grid-stack' class selector) | ###### Returns [`GridStack`](#gridstack-1) ###### Example ```ts const grid = GridStack.init(); Note: the HTMLElement (of type GridHTMLElement) will store a `gridstack: GridStack` value that can be retrieve later const grid = document.querySelector('.grid-stack').gridstack; ``` ##### initAll() ```ts static initAll(options, selector): GridStack[]; ``` Defined in: [gridstack.ts:118](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L118) Will initialize a list of elements (given a selector) and return an array of grids. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `options` | [`GridStackOptions`](#gridstackoptions) | `{}` | grid options (optional) | | `selector` | `string` | `'.grid-stack'` | elements selector to convert to grids (default to '.grid-stack' class selector) | ###### Returns [`GridStack`](#gridstack-1)[] ###### Example ```ts const grids = GridStack.initAll(); grids.forEach(...) ``` ##### isAreaEmpty() ```ts isAreaEmpty( x, y, w, h): boolean; ``` Defined in: [gridstack.ts:1226](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1226) Checks if the specified rectangular area is empty (no widgets occupy any part of it). ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `x` | `number` | the x coordinate (column) of the area to check | | `y` | `number` | the y coordinate (row) of the area to check | | `w` | `number` | the width in columns of the area to check | | `h` | `number` | the height in rows of the area to check | ###### Returns `boolean` true if the area is completely empty, false if any widget overlaps ###### Example ```ts // Check if a 2x2 area at position (1,1) is empty if (grid.isAreaEmpty(1, 1, 2, 2)) { console.log('Area is available for placement'); } ``` ##### isIgnoreChangeCB() ```ts isIgnoreChangeCB(): boolean; ``` Defined in: [gridstack.ts:1107](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1107) 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. ###### Returns `boolean` true if change callbacks are currently being ignored ###### Example ```ts if (!grid.isIgnoreChangeCB()) { // Process the change event console.log('Grid layout changed'); } ``` ##### load() ```ts load(items, addRemove): GridStack; ``` Defined in: [gridstack.ts:722](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L722) 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()`). ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `items` | [`GridStackWidget`](#gridstackwidget)[] | list of widgets definition to update/create | | `addRemove` | `boolean` \| [`AddRemoveFcn`](#addremovefcn) | 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. | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // 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); ``` ###### See [http://gridstackjs.com/demo/serialization.html](http://gridstackjs.com/demo/serialization.html) for complete example ##### makeSubGrid() ```ts makeSubGrid( el, ops?, nodeToAdd?, saveContent?): GridStack; ``` Defined in: [gridstack.ts:506](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L506) Convert an existing gridItem element into a sub-grid with the given (optional) options, else inherit them from the parent's subGrid options. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `el` | [`GridItemHTMLElement`](#griditemhtmlelement) | `undefined` | gridItem element to convert | | `ops?` | [`GridStackOptions`](#gridstackoptions) | `undefined` | (optional) sub-grid options, else default to node, then parent settings, else defaults | | `nodeToAdd?` | [`GridStackNode`](#gridstacknode-2) | `undefined` | (optional) node to add to the newly created sub grid (used when dragging over existing regular item) | | `saveContent?` | `boolean` | `true` | if true (default) the html inside .grid-stack-content will be saved to child widget | ###### Returns [`GridStack`](#gridstack-1) newly created grid ##### makeWidget() ```ts makeWidget(els, options?): GridItemHTMLElement; ``` Defined in: [gridstack.ts:1254](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1254) 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. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `els` | [`GridStackElement`](#gridstackelement) | widget or single selector to convert. | | `options?` | [`GridStackWidget`](#gridstackwidget) | widget definition to use instead of reading attributes or using default sizing values | ###### Returns [`GridItemHTMLElement`](#griditemhtmlelement) the converted GridItemHTMLElement ###### Example ```ts 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}); ``` ##### margin() ```ts margin(value): GridStack; ``` Defined in: [gridstack.ts:1759](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1759) 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. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `value` | [`numberOrString`](#numberorstring) | margin value - can be: - Single number: `10` (applies to all sides) - Two values: `'10px 20px'` (top/bottom, left/right) - Four values: `'10px 20px 5px 15px'` (top, right, bottom, left) | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts grid.margin(10); // 10px all sides grid.margin('10px 20px'); // 10px top/bottom, 20px left/right grid.margin('5px 10px 15px 20px'); // Different for each side ``` ##### movable() ```ts movable(els, val): GridStack; ``` Defined in: [gridstack.ts:2233](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2233) 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. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `els` | [`GridStackElement`](#gridstackelement) | widget element(s) or selector to modify | | `val` | `boolean` | if true widget will be draggable, assuming the parent grid isn't noMove or static | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Make specific widgets draggable grid.movable('.my-widget', true); // Disable dragging for specific widgets grid.movable('#fixed-widget', false); ``` ##### off() ```ts off(name): GridStack; ``` Defined in: [gridstack.ts:1350](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1350) unsubscribe from the 'on' event GridStackEvent ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `name` | `string` | of the event (see possible values) or list of names space separated | ###### Returns [`GridStack`](#gridstack-1) ##### offAll() ```ts offAll(): GridStack; ``` Defined in: [gridstack.ts:1377](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1377) Remove all event handlers from the grid. This is useful for cleanup when destroying a grid. ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts grid.offAll(); // Remove all event listeners ``` ##### on() ###### Call Signature ```ts on(name, callback): GridStack; ``` Defined in: [gridstack.ts:1313](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1313) 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 grid - `change`: Occurs when widgets change their position/size due to constraints or direct changes - `disable`: Called when grid becomes disabled - `dragstart`: Called when grid item starts being dragged - `drag`: 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 attributes - `dropped`: Called when an item has been dropped and accepted over a grid - `enable`: Called when grid becomes enabled - `removed`: Called when items are being removed from the grid - `resizestart`: Called before user starts resizing an item - `resize`: 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 attributes ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `name` | `"dropped"` | event name(s) to listen for (space separated for multiple) | | `callback` | [`GridStackDroppedHandler`](#gridstackdroppedhandler) | function to call when event occurs | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Listen to multiple events at once grid.on('added removed change', (event, items) => { items.forEach(item => console.log('Item changed:', item)); }); // Listen to individual events grid.on('added', (event, items) => { items.forEach(item => console.log('Added item:', item)); }); ``` ###### Call Signature ```ts on(name, callback): GridStack; ``` Defined in: [gridstack.ts:1314](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1314) 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 grid - `change`: Occurs when widgets change their position/size due to constraints or direct changes - `disable`: Called when grid becomes disabled - `dragstart`: Called when grid item starts being dragged - `drag`: 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 attributes - `dropped`: Called when an item has been dropped and accepted over a grid - `enable`: Called when grid becomes enabled - `removed`: Called when items are being removed from the grid - `resizestart`: Called before user starts resizing an item - `resize`: 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 attributes ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `name` | `"enable"` \| `"disable"` | event name(s) to listen for (space separated for multiple) | | `callback` | [`GridStackEventHandler`](#gridstackeventhandler) | function to call when event occurs | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Listen to multiple events at once grid.on('added removed change', (event, items) => { items.forEach(item => console.log('Item changed:', item)); }); // Listen to individual events grid.on('added', (event, items) => { items.forEach(item => console.log('Added item:', item)); }); ``` ###### Call Signature ```ts on(name, callback): GridStack; ``` Defined in: [gridstack.ts:1315](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1315) 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 grid - `change`: Occurs when widgets change their position/size due to constraints or direct changes - `disable`: Called when grid becomes disabled - `dragstart`: Called when grid item starts being dragged - `drag`: 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 attributes - `dropped`: Called when an item has been dropped and accepted over a grid - `enable`: Called when grid becomes enabled - `removed`: Called when items are being removed from the grid - `resizestart`: Called before user starts resizing an item - `resize`: 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 attributes ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `name` | `"change"` \| `"added"` \| `"removed"` \| `"resizecontent"` | event name(s) to listen for (space separated for multiple) | | `callback` | [`GridStackNodesHandler`](#gridstacknodeshandler) | function to call when event occurs | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Listen to multiple events at once grid.on('added removed change', (event, items) => { items.forEach(item => console.log('Item changed:', item)); }); // Listen to individual events grid.on('added', (event, items) => { items.forEach(item => console.log('Added item:', item)); }); ``` ###### Call Signature ```ts on(name, callback): GridStack; ``` Defined in: [gridstack.ts:1316](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1316) 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 grid - `change`: Occurs when widgets change their position/size due to constraints or direct changes - `disable`: Called when grid becomes disabled - `dragstart`: Called when grid item starts being dragged - `drag`: 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 attributes - `dropped`: Called when an item has been dropped and accepted over a grid - `enable`: Called when grid becomes enabled - `removed`: Called when items are being removed from the grid - `resizestart`: Called before user starts resizing an item - `resize`: 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 attributes ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `name` | \| `"drag"` \| `"dragstart"` \| `"resize"` \| `"resizestart"` \| `"resizestop"` \| `"dragstop"` | event name(s) to listen for (space separated for multiple) | | `callback` | [`GridStackElementHandler`](#gridstackelementhandler) | function to call when event occurs | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Listen to multiple events at once grid.on('added removed change', (event, items) => { items.forEach(item => console.log('Item changed:', item)); }); // Listen to individual events grid.on('added', (event, items) => { items.forEach(item => console.log('Added item:', item)); }); ``` ###### Call Signature ```ts on(name, callback): GridStack; ``` Defined in: [gridstack.ts:1317](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1317) 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 grid - `change`: Occurs when widgets change their position/size due to constraints or direct changes - `disable`: Called when grid becomes disabled - `dragstart`: Called when grid item starts being dragged - `drag`: 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 attributes - `dropped`: Called when an item has been dropped and accepted over a grid - `enable`: Called when grid becomes enabled - `removed`: Called when items are being removed from the grid - `resizestart`: Called before user starts resizing an item - `resize`: 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 attributes ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `name` | `string` | event name(s) to listen for (space separated for multiple) | | `callback` | [`GridStackEventHandlerCallback`](#gridstackeventhandlercallback) | function to call when event occurs | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Listen to multiple events at once grid.on('added removed change', (event, items) => { items.forEach(item => console.log('Item changed:', item)); }); // Listen to individual events grid.on('added', (event, items) => { items.forEach(item => console.log('Added item:', item)); }); ``` ##### onResize() ```ts onResize(clientWidth): GridStack; ``` Defined in: [gridstack.ts:2030](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2030) 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. ###### Parameters | Parameter | Type | | ------ | ------ | | `clientWidth` | `number` | ###### Returns [`GridStack`](#gridstack-1) ##### prepareDragDrop() ```ts prepareDragDrop(el, force?): GridStack; ``` Defined in: [gridstack.ts:2716](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2716) prepares the element for drag&drop - this is normally called by makeWidget() unless are are delay loading ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `el` | [`GridItemHTMLElement`](#griditemhtmlelement) | `undefined` | GridItemHTMLElement of the widget | | `force?` | `boolean` | `false` | | ###### Returns [`GridStack`](#gridstack-1) ##### registerEngine() ```ts static registerEngine(engineClass): void; ``` Defined in: [gridstack.ts:172](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L172) call this method to register your engine instead of the default one. See instead `GridStackOptions.engineClass` if you only need to replace just one instance. ###### Parameters | Parameter | Type | | ------ | ------ | | `engineClass` | *typeof* [`GridStackEngine`](#gridstackengine-2) | ###### Returns `void` ##### removeAll() ```ts removeAll(removeDOM, triggerEvent): GridStack; ``` Defined in: [gridstack.ts:1426](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1426) Removes all widgets from the grid. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `removeDOM` | `boolean` | `true` | if `false` DOM elements won't be removed from the tree (Default? `true`). | | `triggerEvent` | `boolean` | `true` | if `false` (quiet mode) element will not be added to removed list and no 'removed' callbacks will be called (Default? true). | ###### Returns [`GridStack`](#gridstack-1) ##### removeAsSubGrid() ```ts removeAsSubGrid(nodeThatRemoved?): void; ``` Defined in: [gridstack.ts:599](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L599) 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) ###### Parameters | Parameter | Type | | ------ | ------ | | `nodeThatRemoved?` | [`GridStackNode`](#gridstacknode-2) | ###### Returns `void` ##### removeWidget() ```ts removeWidget( els, removeDOM, triggerEvent): GridStack; ``` Defined in: [gridstack.ts:1388](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1388) Removes widget from the grid. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `els` | [`GridStackElement`](#gridstackelement) | `undefined` | - | | `removeDOM` | `boolean` | `true` | if `false` DOM element won't be removed from the tree (Default? true). | | `triggerEvent` | `boolean` | `true` | if `false` (quiet mode) element will not be added to removed list and no 'removed' callbacks will be called (Default? true). | ###### Returns [`GridStack`](#gridstack-1) ##### resizable() ```ts resizable(els, val): GridStack; ``` Defined in: [gridstack.ts:2259](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L2259) Enables/Disables user resizing for specific grid elements. For all items and future items, use enableResize() instead. No-op for static grids. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `els` | [`GridStackElement`](#gridstackelement) | widget element(s) or selector to modify | | `val` | `boolean` | if true widget will be resizable, assuming the parent grid isn't noResize or static | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Make specific widgets resizable grid.resizable('.my-widget', true); // Disable resizing for specific widgets grid.resizable('#fixed-size-widget', false); ``` ##### resizeToContent() ```ts resizeToContent(el): void; ``` Defined in: [gridstack.ts:1649](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1649) 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. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `el` | [`GridItemHTMLElement`](#griditemhtmlelement) | the grid item element to resize | ###### Returns `void` ###### Example ```ts // Resize a widget to fit its content const widget = document.querySelector('.grid-stack-item'); grid.resizeToContent(widget); // This is commonly used with dynamic content: widget.querySelector('.content').innerHTML = 'New longer content...'; grid.resizeToContent(widget); ``` ##### rotate() ```ts rotate(els, relative?): GridStack; ``` Defined in: [gridstack.ts:1724](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1724) 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. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `els` | [`GridStackElement`](#gridstackelement) | widget element(s) or selector to rotate | | `relative?` | [`Position`](#position-1) | optional pixel coordinate relative to upper/left corner to rotate around (keeps that cell under cursor) | ###### Returns [`GridStack`](#gridstack-1) the grid instance for chaining ###### Example ```ts // Rotate a specific widget grid.rotate('.my-widget'); // Rotate with relative positioning during drag grid.rotate(widget, { left: 50, top: 30 }); ``` ##### save() ```ts save( saveContent, saveGridOpt, saveCB, column?): | GridStackOptions | GridStackWidget[]; ``` Defined in: [gridstack.ts:634](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L634) saves the current layout returning a list of widgets for serialization which might include any nested grids. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `saveContent` | `boolean` | `true` | if true (default) the latest html inside .grid-stack-content will be saved to GridStackWidget.content field, else it will be removed. | | `saveGridOpt` | `boolean` | `false` | 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. | | `saveCB` | [`SaveFcn`](#savefcn) | `GridStack.saveCB` | callback for each node -> widget, so application can insert additional data to be saved into the widget data structure. | | `column?` | `number` | `undefined` | if 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. | ###### Returns \| [`GridStackOptions`](#gridstackoptions) \| [`GridStackWidget`](#gridstackwidget)[] list of widgets or full grid option, including .children list of widgets ##### setAnimation() ```ts setAnimation(doAnimate, delay?): GridStack; ``` Defined in: [gridstack.ts:1445](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1445) Toggle the grid animation state. Toggles the `grid-stack-animate` class. ###### Parameters | Parameter | Type | Description | | ------ | ------ | ------ | | `doAnimate` | `boolean` | if true the grid will animate. | | `delay?` | `boolean` | if true setting will be set on next event loop. | ###### Returns [`GridStack`](#gridstack-1) ##### setStatic() ```ts setStatic( val, updateClass, recurse): GridStack; ``` Defined in: [gridstack.ts:1468](https://github.com/adumesny/gridstack.js/blob/master/src/gridstack.ts#L1468) 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. ###### Parameters | Parameter | Type | Default value | Description | | ------ | ------ | ------ | ------ | | `val` | `boolean` | `undefined` | if true the grid become static. | | `updateClass` | `boolean` | `true` | true (default) if css class gets updated | | `recurse` | `boolean` | `true` | true (default) if sub-grids also get updated | ###### Returns [`GridStack`](#gridstack-1) ##### setupDragIn() ```ts static s