### Barebones Grid Example
Source: https://github.com/haltu/muuri/blob/master/docs/examples.md
Demonstrates the fundamental setup of a Muuri grid. This example serves as a starting point for creating basic grid layouts.
```html
```
--------------------------------
### Install Dependencies
Source: https://github.com/haltu/muuri/blob/master/CONTRIBUTING.md
Installs project dependencies. This is a prerequisite for running development commands.
```bash
npm install
```
--------------------------------
### Basic Sorting Example
Source: https://github.com/haltu/muuri/blob/master/docs/examples.md
Illustrates how to implement basic sorting functionality within a Muuri grid. This example is useful for scenarios requiring dynamic reordering of grid items.
```html
```
--------------------------------
### Install Muuri via npm
Source: https://github.com/haltu/muuri/blob/master/docs/getting-started.md
Use npm to install the Muuri library for your project. This is the recommended method for most modern JavaScript development.
```bash
npm install muuri
```
--------------------------------
### Configure Default dragStartPredicate with Object
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Sets the drag start behavior using an object with distance and delay values. Use this for simple configuration of the default drag start logic.
```javascript
var grid = new Muuri(elem, {
dragStartPredicate: {
distance: 10,
delay: 100,
},
});
```
--------------------------------
### Install Web Animations Polyfill via npm
Source: https://github.com/haltu/muuri/blob/master/docs/getting-started.md
Install the Web Animations polyfill using npm if your target browsers do not support the Web Animations API. This ensures animations work consistently.
```bash
npm install web-animations-js
```
--------------------------------
### Custom Drag Start Predicate with Default Fallback
Source: https://github.com/haltu/muuri/blob/master/README.md
Implements a custom drag start predicate that also utilizes the default predicate logic. This example prevents the first item from being dragged and uses the default for others.
```javascript
var grid = new Muuri(elem, {
dragStartPredicate: function (item, e) {
// If this is final event in the drag process, let's prepare the predicate
// for the next round (do some resetting/teardown). The default predicate
// always needs to be called during the final event if there's a chance it
// has been triggered during the drag process because it does some necessary
// state resetting.
if (e.isFinal) {
Muuri.ItemDrag.defaultStartPredicate(item, e);
return;
}
// Prevent first item from being dragged.
if (grid.getItems()[0] === item) {
return false;
}
// For other items use the default drag start predicate.
return Muuri.ItemDrag.defaultStartPredicate(item, e);
},
});
```
--------------------------------
### Listen for Layout Start
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Triggered when the layout procedure begins. Useful for reacting to grid element dimension changes as items are about to be positioned.
```javascript
grid.on('layoutStart', function (items, isInstant) {
console.log(items, isInstant);
});
```
--------------------------------
### dragStart Event
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered at the end of the drag start process when dragging of an item begins.
```APIDOC
## Event: dragStart
### Description
Triggered in the end of the _drag start_ process when dragging of an item begins.
### Arguments
#### item (_Muuri.Item_)
- The dragged item.
#### event (_object_)
- Muuri.Dragger event data.
### Request Example
```javascript
grid.on('dragStart', function (item, event) {
console.log(event);
console.log(item);
});
```
```
--------------------------------
### Listen to dragReleaseStart Event
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Subscribe to the 'dragReleaseStart' event to get a callback when a dragged item is released. The callback receives the released item as a parameter.
```javascript
grid.on('dragReleaseStart', function (item) {
console.log(item);
});
```
--------------------------------
### Listen to dragStart Event
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Use this event listener to execute code when the drag start process begins. It provides the dragged item and Dragger event data.
```javascript
grid.on('dragStart', function (item, event) {
console.log(event);
console.log(item);
});
```
--------------------------------
### Configuring dragSortHeuristics for Smoother Sorting
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Example of how to configure dragSortHeuristics with custom values for sortInterval, minDragDistance, and minBounceBackAngle to achieve smoother drag sorting.
```javascript
var grid = new Muuri(elem, {
dragEnabled: true,
dragSortHeuristics: {
sortInterval: 10,
minDragDistance: 5,
minBounceBackAngle: Math.PI / 2,
},
});
```
--------------------------------
### Build Custom Muuri Layout Algorithm
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Implement a custom layout algorithm by providing a function that calculates item positions and grid styles. This example demonstrates asynchronous calculation and cancellation.
```javascript
var grid = new Muuri(elem, {
layout: function (grid, layoutId, items, width, height, callback) {
var layout = {
id: layoutId,
items: items,
slots: [],
styles: {},
};
// Calculate the slots asynchronously. Note that the timeout is here only
// as an example and does not help at all in the calculations. You should
// offload the calculations to web workers if you want real benefits.
// Also note that doing asynchronous layout is completely optional and you
// can call the callback function synchronously also.
var timerId = window.setTimeout(function () {
var item,
m,
x = 0,
y = 0,
w = 0,
h = 0;
for (var i = 0; i < items.length; i++) {
item = items[i];
x += w;
y += h;
m = item.getMargin();
w = item.getWidth() + m.left + m.right;
h = item.getHeight() + m.top + m.bottom;
layout.slots.push(x, y);
}
w += x;
h += y;
// Set the CSS styles that should be applied to the grid element.
layout.styles.width = w + 'px';
layout.styles.height = h + 'px';
// When the layout is fully computed let's call the callback function and
// provide the layout object as it's argument.
callback(layout);
}, 200);
// If you are doing an async layout you _can_ (if you want to) return a
// function that cancels this specific layout calculations if it's still
// processing/queueing when the next layout is requested.
return function () {
window.clearTimeout(timerId);
};
},
});
```
--------------------------------
### Pooling Placeholder Elements with dragPlaceholder
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Demonstrates how to pool placeholder elements for performance and memory efficiency when using the dragPlaceholder option. This example shows custom createElement, onCreate, and onRemove callbacks.
```javascript
// This example showcases how to pool placeholder elements
// for better performance and memory efficiency.
var phPool = [];
var phElem = document.createElement('div');
var grid = new Muuri(elem, {
dragEnabled: true,
dragPlaceholder: {
enabled: true,
createElement(item) {
return phPool.pop() || phElem.cloneNode();
},
onCreate(item, element) {
// If you want to do something after the
// placeholder is fully created, here's
// the place to do it.
},
onRemove(item, element) {
phPool.push(element);
},
},
});
```
--------------------------------
### Provide Custom dragStartPredicate Function
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Implements a custom drag start logic by providing a function. This function is called until it returns true or false, controlling when the item begins to move.
```javascript
var grid = new Muuri(elem, {
dragStartPredicate: function (item, e) {
// Start moving the item after the item has been dragged for one second.
if (e.deltaTime > 1000) {
return true;
}
},
});
```
--------------------------------
### Get Grid Instance
Source: https://github.com/haltu/muuri/blob/master/docs/item-methods.md
Retrieves the grid instance to which the item belongs. Use this when you need to interact with the grid from an item context.
```javascript
const grid = item.getGrid();
```
--------------------------------
### Listen to destroy Event
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Subscribe to the 'destroy' event to get a callback after the grid has been destroyed. This is useful for cleanup operations.
```javascript
grid.on('destroy', function () {
console.log('Muuri is no more...');
});
```
--------------------------------
### Custom dragStartPredicate with Default Fallback
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Combines custom drag start logic with the default predicate. This is useful for specific item exclusions or behaviors while allowing the default logic to handle other cases.
```javascript
var grid = new Muuri(elem, {
dragStartPredicate: function (item, e) {
// If this is final event in the drag process, let's prepare the predicate
// for the next round (do some resetting/teardown). The default predicate
// always needs to be called during the final event if there's a chance it
// has been triggered during the drag process because it does some necessary
// state resetting.
if (e.isFinal) {
Muuri.ItemDrag.defaultStartPredicate(item, e);
return;
}
// Prevent first item from being dragged.
if (grid.getItems()[0] === item) {
return false;
}
// For other items use the default drag start predicate.
return Muuri.ItemDrag.defaultStartPredicate(item, e);
},
});
```
--------------------------------
### layoutAbort Event
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered if a new layout process is started while the current one is still positioning items.
```APIDOC
## layoutAbort Event
### Description
Triggered if you start a new layout process (`grid.layout()`) while the current layout process is still busy positioning items. Note that this event is not triggered if you start a new layout process while the layout is being computed and the items have not yet started positioning.
### Arguments
- **items** (_array_) - The items that were attempted to be positioned. Note that these items are always identical to what the _layoutStart_ event's callback receives as it's argument.
### Request Example
```javascript
grid.on('layoutAbort', function (items) {
console.log(items);
// For good measure you might want to filter out all the non-active items,
// because it's techniclly possible that some of the items are destroyed or
// hidden when we receive this event.
var activeItems = items.filter(function (item) {
return item.isActive();
});
});
```
```
--------------------------------
### Add Items to Muuri Grid
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Demonstrates adding new items to a Muuri grid. The first example adds items to the end, the second to the beginning, and the third disables the automatic layout after adding.
```javascript
var newItemsA = grid.add([elemA, elemB]);
```
```javascript
var newItemsB = grid.add([elemA, elemB], { index: 0 });
```
```javascript
var newItemsC = grid.add([elemA, elemB], { layout: false });
```
--------------------------------
### Basic Vertical Grid with Dragging
Source: https://github.com/haltu/muuri/blob/master/docs/examples.md
Showcases a basic vertical Muuri grid that supports item dragging. This example is suitable for applications where users need to rearrange items vertically.
```html
```
--------------------------------
### Get All or Specific Grid Items
Source: https://github.com/haltu/muuri/blob/master/README.md
Retrieve all items in the grid, or a subset based on provided targets (indices, elements, or Muuri.Item instances).
```javascript
// Get all items, both active and inactive.
var allItems = grid.getItems();
// Get all active items.
var activeItems = grid.getItems().filter(function (item) {
return item.isActive();
});
// Get all positioning items.
var positioningItems = grid.getItems().filter(function (item) {
return item.isPositioning();
});
// Get the first item.
var firstItem = grid.getItems(0)[0];
// Get specific items by their elements.
var items = grid.getItems([elemA, elemB]);
```
--------------------------------
### Get Grid Instance from Item
Source: https://github.com/haltu/muuri/blob/master/README.md
Retrieves the Muuri grid instance to which the item belongs. Useful for accessing grid-level methods from an item context.
```javascript
var grid = item.getGrid();
```
--------------------------------
### Configure Grid with dragAutoScroll
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Sets up a Muuri grid with drag and drop enabled, configuring advanced auto-scroll behavior for dragged items. This includes defining multiple scroll targets, setting scroll thresholds, safe zones, dynamic speeds, and callback functions for scroll start and stop events.
```javascript
var dragContainer = document.createElement('div');
dragContainer.style.position = 'fixed';
dragContainer.style.left = '0px';
dragContainer.style.top = '0px';
dragContainer.style.zIndex = 1000;
document.body.appendChild(dragContainer);
var grid = new Muuri(elem, {
dragEnabled: true,
dragContainer: dragContainer,
dragAutoScroll: {
targets: [
// Scroll window on both x-axis and y-axis.
{ element: window, priority: 0 },
// Scroll scrollElement (can be any scrollable element) on y-axis only,
// and prefer it over window in conflict scenarios.
{ element: scrollElement, priority: 1, axis: Muuri.AutoScroller.AXIS_Y },
],
// Let's use the dragged item element as the handle.
handle: null,
// Start auto-scroll when the distance from scroll target's edge to dragged
// item is 40px or less.
threshold: 40,
// Make sure the inner 10% of the scroll target's area is always "safe zone"
// which does not trigger auto-scroll.
safeZone: 0.1,
// Let's define smooth dynamic speed.
// Max speed: 2000 pixels per second
// Acceleration: 2700 pixels per second
// Deceleration: 3200 pixels per second.
speed: Muuri.AutoScroller.smoothSpeed(2000, 2700, 3200),
// Let's not sort during scroll.
sortDuringScroll: false,
// Enable smooth stop.
smoothStop: true,
// Finally let's log some data when auto-scroll starts and stops.
onStart: function (item, scrollElement, direction) {
console.log('AUTOSCROLL STARTED', item, scrollElement, direction);
},
onStop: function (item, scrollElement, direction) {
console.log('AUTOSCROLL STOPPED', item, scrollElement, direction);
},
},
});
```
--------------------------------
### receive Event
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered for the receiving grid at the end of the send process, before the item's layout starts. Useful for actions after an item has been received.
```APIDOC
## Event: receive
### Description
Triggered for the receiving grid in the end of the _send process_ (after `grid.send()` is called or when an item is dragged into another grid). Note that this event is called _before_ the item's layout starts.
### Arguments
#### data (object)
- **data.item** (_Muuri.Item_) - The item that was sent.
- **data.fromGrid** (_Muuri_) - The grid the item was sent from.
- **data.fromIndex** (_number_) - The index the item was moved from.
- **data.toGrid** (_Muuri_) - The grid the item was sent to.
- **data.toIndex** (_number_) - The index the item was moved to.
### Request Example
```javascript
grid.on('receive', function (data) {
console.log(data);
});
```
```
--------------------------------
### dragInit Event
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered at the beginning of the drag start process when dragging of an item begins. Useful for manipulating the dragged item before it's appended to the dragContainer.
```APIDOC
## Event: dragInit
### Description
Triggered in the beginning of the _drag start_ process when dragging of an item begins. This event is highly useful in situations where you need to manipulate the dragged item (freeze it's dimensions for example) before it is appended to the [dragContainer](#dragcontainer-).
### Arguments
#### item (_Muuri.Item_)
- The dragged item.
#### event (_object_)
- Muuri.Dragger event data.
### Request Example
```javascript
grid.on('dragInit', function (item, event) {
console.log(event);
console.log(item);
});
```
```
--------------------------------
### Get All Grid Items
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Retrieves all items within the grid, including both active and inactive ones. This method can also accept targets to fetch specific items.
```javascript
// Get all items, both active and inactive.
var allItems = grid.getItems();
// Get all active items.
var activeItems = grid.getItems().filter(function (item) {
return item.isActive();
});
// Get all positioning items.
var positioningItems = grid.getItems().filter(function (item) {
return item.isPositioning();
});
// Get the first item.
var firstItem = grid.getItems(0)[0];
// Get specific items by their elements.
var items = grid.getItems([elemA, elemB]);
```
--------------------------------
### Initialize Muuri Grid with Options
Source: https://github.com/haltu/muuri/blob/master/README.md
Create a new Muuri grid instance and provide specific configuration options.
```javascript
// Providing some options.
var gridB = new Muuri('.grid-b', {
items: '.item',
});
```
--------------------------------
### Initialize Muuri Grid with Minimum Configuration
Source: https://github.com/haltu/muuri/blob/master/README.md
Create a new Muuri grid instance with the minimum required configuration.
```javascript
// Minimum configuration.
var gridA = new Muuri('.grid-a');
```
--------------------------------
### Get Grid Item by Index or Element
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Retrieves a specific grid item. You can target an item by its numerical index, its DOM element, or an existing Muuri.Item instance. Returns null if the item is not found.
```javascript
// Get first item in grid.
var itemA = grid.getItem(0);
// Get item by element reference.
var itemB = grid.getItem(someElement);
```
--------------------------------
### send
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered for the originating grid at the end of the send process, after `grid.send()` is called or when an item is dragged into another grid. This event is called before the item's layout starts.
```APIDOC
## event: send
### Description
Triggered for the originating grid in the end of the _send process_ (after `grid.send()` is called or when an item is dragged into another grid). Note that this event is called _before_ the item's layout starts.
### Arguments
- **data** (object)
- **data.item** (Muuri.Item) - The item that was sent.
- **data.fromGrid** (Muuri) - The grid the item was sent from.
- **data.fromIndex** (number) - The index the item was moved from.
- **data.toGrid** (Muuri) - The grid the item was sent to.
- **data.toIndex** (number) - The index the item was moved to.
### Example
```javascript
grid.on('send', function (data) {
console.log(data);
});
```
```
--------------------------------
### Define Custom Sort Data
Source: https://github.com/haltu/muuri/blob/master/README.md
Provide custom functions to retrieve sortable data from grid items. This example defines getters for 'foo' (numeric) and 'bar' (string) attributes. Remember to call 'refreshSortData' after updating item data and 'sort' to reorder the grid.
```javascript
var grid = new Muuri(elem, {
sortData: {
foo: function (item, element) {
return parseFloat(element.getAttribute('data-foo'));
},
bar: function (item, element) {
return element.getAttribute('data-bar').toUpperCase();
},
},
});
grid.refreshSortData();
grid.sort('foo bar');
```
--------------------------------
### Listen to showStart Event
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Triggered just before items are shown. Logs the items that are about to be displayed.
```javascript
grid.on('showStart', function (items) {
console.log(items);
});
```
--------------------------------
### showStart
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered just before items are shown after `grid.show()` is called.
```APIDOC
## event: showStart
### Description
Triggered after `grid.show()` is called, just before the items are shown.
### Arguments
- **items** (array) - The items that are about to be shown.
### Example
```javascript
grid.on('showStart', function (items) {
console.log(items);
});
```
```
--------------------------------
### layoutStart
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Triggered when the layout procedure begins, right after a new layout has been generated and internal item positions have been updated.
```APIDOC
## layoutStart
### Description
Triggered when the the layout procedure begins. More specifically, this event is emitted right after new _layout_ has been generated, internal item positions updated and grid element's dimensions updated. After this event is emitted the items in the layout will be positioned to their new positions. So if you e.g. want to react to grid element dimension changes this is a good place to do that.
### Method
`grid.on('layoutStart', callback)`
### Parameters
#### Listener parameters
- **items** (_array_) - The items that are about to be positioned.
- **isInstant** (_boolean_) - Was the layout called with `instant` flag or not.
### Request Example
```javascript
grid.on('layoutStart', function (items, isInstant) {
console.log(items, isInstant);
});
```
### Response
None
```
--------------------------------
### Enable Layout on Resize (Instant)
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Set `layoutOnResize` to `true` to enable instant layout triggering on window resize.
```javascript
var grid = new Muuri(elem, {
layoutOnResize: true,
});
```
--------------------------------
### Get Item Element
Source: https://github.com/haltu/muuri/blob/master/docs/item-methods.md
Retrieves the DOM element associated with the item. This is useful for direct DOM manipulation or inspection.
```javascript
const elem = item.getElement();
```
--------------------------------
### Scrolling Only Y-Axis
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Example of configuring the 'axis' property to scroll only the vertical axis. This is useful when horizontal scrolling is not desired or applicable.
```javascript
Muuri.AutoScroller.AXIS_Y
```
--------------------------------
### Scrolling Only X-Axis
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Example of configuring the 'axis' property to scroll only the horizontal axis. This is useful when vertical scrolling is not desired or applicable.
```javascript
Muuri.AutoScroller.AXIS_X
```
--------------------------------
### Initialize Grid with NodeList Items
Source: https://github.com/haltu/muuri/blob/master/README.md
Configure a Muuri grid to use a NodeList, typically obtained via querySelectorAll, as its items.
```javascript
// Use node list.
var grid = new Muuri(elem, {
items: elem.querySelectorAll('.item'),
});
```
--------------------------------
### Filter Items by Class
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Filters grid items to show only those with a specific class. This example uses a CSS selector for filtering.
```javascript
grid.filter('.foo');
```
--------------------------------
### Filter Items by Attribute
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Filters grid items to show only those with a specific attribute. This example demonstrates using a predicate function.
```javascript
grid.filter(function (item) {
return item.getElement().hasAttribute('data-foo');
});
```
--------------------------------
### Grid Constructor
Source: https://github.com/haltu/muuri/blob/master/README.md
Initializes a new Muuri grid instance. It takes a grid element and an optional options object to configure the grid's behavior and appearance.
```APIDOC
## Grid Constructor
### Description
Initializes a new Muuri grid instance. It takes a grid element and an optional options object to configure the grid's behavior and appearance.
### Signature
`new Muuri(gridElement, options)`
### Parameters
#### Path Parameters
- **gridElement** (HTMLElement) - Required - The DOM element that will act as the grid container.
- **options** (Object) - Optional - An object containing configuration options for the grid.
### Options
Refer to the [Grid Options](#grid-options) section for a full list of configurable options.
```
--------------------------------
### Filter Items by Selector
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Filters grid items using a CSS selector. This example shows how to filter items that have a specific attribute.
```javascript
grid.filter('[data-foo]');
```
--------------------------------
### Run Unit Tests
Source: https://github.com/haltu/muuri/blob/master/CONTRIBUTING.md
Executes unit tests for Muuri. Requires `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` in an `.env` file. Launches browsers by default.
```bash
npm run test
```
--------------------------------
### Initialize Muuri Grid
Source: https://github.com/haltu/muuri/blob/master/docs/getting-started.md
Instantiate Muuri with the grid element selector. This is the minimum required step to make the grid functional.
```javascript
var grid = new Muuri('.grid');
```
--------------------------------
### Get Item Height
Source: https://github.com/haltu/muuri/blob/master/docs/item-methods.md
Retrieves the cached height of the item's element, including padding and borders. Use this for layout calculations.
```javascript
const height = item.getHeight();
```
--------------------------------
### Get Item Width
Source: https://github.com/haltu/muuri/blob/master/docs/item-methods.md
Retrieves the cached width of the item's element, including padding and borders. Use this for layout calculations.
```javascript
const width = item.getWidth();
```
--------------------------------
### Format, Build, and Test Changes
Source: https://github.com/haltu/muuri/blob/master/CONTRIBUTING.md
A sequence of commands to ensure code is formatted, built, and tested before creating a pull request. This is a crucial step in the contribution workflow.
```bash
npm run format && npm run build && npm run test
```
--------------------------------
### showStart Event
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Triggered after `grid.show()` is called, just before the items are shown. It provides the items that are about to be displayed.
```APIDOC
## showStart Event
### Description
Triggered after `grid.show()` is called, just before the items are shown. It provides the items that are about to be displayed.
### Listener Parameters
- **items** (array) - The items that are about to be shown.
### Example
```javascript
grid.on('showStart', function (items) {
console.log(items);
});
```
```
--------------------------------
### Grid Constructor
Source: https://github.com/haltu/muuri/blob/master/README.md
Instantiates a new Muuri grid. The grid element must be positioned, and items must be absolutely positioned.
```APIDOC
## Muuri Grid Constructor
### Description
Instantiates a new Muuri grid. The grid element must be positioned, and items must be absolutely positioned.
### Syntax
`Muuri( element, [options] )
### Parameters
- **element** (_element_ / _string_) - The grid element or a selector string. Defaults to `null`.
- **options** (_object_) - Optional configuration object. See [detailed options reference](#grid-options).
### Default Options
The default configuration object for Muuri grids, covering items, animations, layout, sorting, drag & drop, and class names.
```
--------------------------------
### Specify Initial Items for Muuri Grid
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Configure the initial items for a Muuri grid by providing an array of elements, a NodeList, or a CSS selector.
```javascript
var grid = new Muuri(elem, {
items: [elemA, elemB, elemC],
});
```
```javascript
var grid = new Muuri(elem, {
items: elem.querySelectorAll('.item'),
});
```
```javascript
var grid = new Muuri(elem, {
items: '.item',
});
```
--------------------------------
### Initialize Grid with Specific Item Elements
Source: https://github.com/haltu/muuri/blob/master/README.md
Configure a Muuri grid to use a specific array of DOM elements as its items.
```javascript
// Use specific items.
var grid = new Muuri(elem, {
items: [elemA, elemB, elemC],
});
```
--------------------------------
### Listen to dragReleaseEnd Event
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Subscribe to the 'dragReleaseEnd' event to get a callback after a released item has finished its position animation. The callback receives the released item.
```javascript
grid.on('dragReleaseEnd', function (item) {
console.log(item);
});
```
--------------------------------
### item.getPosition()
Source: https://github.com/haltu/muuri/blob/master/docs/item-methods.md
Gets the cached position of the item in pixels, relative to the grid element. This indicates the item's current placement within the grid layout.
```APIDOC
## getPosition
### Description
Get item element's cached position (in pixels, relative to the grid element).
### Method
`item.getPosition()`
### Returns
- **object** - An object containing the position values.
- **obj.left** (number)
- **obj.top** (number)
### Example
```javascript
const position = item.getPosition();
```
```
--------------------------------
### grid.on('dragReleaseStart', ...)
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered immediately after a dragged item is released.
```APIDOC
## event: dragReleaseStart
### Description
Triggered when a dragged item is released (always after `dragEnd` event).
### Arguments
- **item** (_Muuri.Item_) - The released item.
```
--------------------------------
### grid.show
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Shows targeted items in the grid, with options to control animation, synchronization with layout, and callbacks.
```APIDOC
## grid.show
### Description
Shows targeted items in the grid, with options to control animation, synchronization with layout, and callbacks.
### Method
`grid.show( items, [options] )`
### Parameters
#### Path Parameters
- **items** (array) - Required - An array of item instances.
#### Query Parameters
- **options.instant** (boolean) - Optional - Should the items be shown instantly without any possible animation? Default value: `false`.
- **options.syncWithLayout** (boolean) - Optional - Should we wait for the next layout's calculations to finish before starting the show animations? By default this option is enabled. Default value: `true`.
- **options.onFinish** (function) - Optional - A callback function that is called after the items are shown.
- **options.layout** (boolean / function / string) - Optional - Controls the layout call. Can be `false` to disable, a callback function, or `'instant'` for immediate layout. Default value: `true`.
### Response
#### Success Response
- **Muuri** - Returns the grid instance.
### Request Example
```javascript
// Show items with animation (if any).
grid.show([itemA, itemB]);
// Show items instantly without animations.
grid.show([itemA, itemB], { instant: true });
// Show items with callback (and with animations if any).
grid.show([itemA, itemB], {
onFinish: function (items) {
console.log('items shown!');
},
});
```
```
--------------------------------
### Build Muuri
Source: https://github.com/haltu/muuri/blob/master/CONTRIBUTING.md
Builds the production-ready JavaScript files for Muuri. This command generates `dist/muuri.js` and `dist/muuri.min.js`.
```bash
npm run build
```
--------------------------------
### Get Item Position
Source: https://github.com/haltu/muuri/blob/master/docs/item-methods.md
Retrieves the cached position of the item's element relative to the grid in pixels. The returned object contains left and top properties.
```javascript
const position = item.getPosition();
```
--------------------------------
### Get Item Margins
Source: https://github.com/haltu/muuri/blob/master/docs/item-methods.md
Retrieves the cached margins of the item's element in pixels. The returned object contains left, right, top, and bottom properties.
```javascript
const margin = item.getMargin();
```
--------------------------------
### Show Items with Callback
Source: https://github.com/haltu/muuri/blob/master/README.md
Shows items and executes a callback function upon completion. Ideal for chaining actions after items are displayed.
```javascript
// Show items with callback (and with animations if any).
grid.show([itemA, itemB], {
onFinish: function (items) {
console.log('items shown!');
},
});
```
--------------------------------
### Get Grid Element
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Retrieves the main DOM element associated with the Muuri grid instance. Use this when you need to directly manipulate the grid's container element.
```javascript
var elem = grid.getElement();
```
--------------------------------
### grid.on
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Binds an event listener to the grid instance. It allows you to react to various grid events.
```APIDOC
## grid.on
### Description
Binds an event listener to the grid instance. It allows you to react to various grid events.
### Method
`grid.on( event, listener )`
### Parameters
#### Parameters
- **event** (string) - The name of the event to listen for.
- **listener** (function) - The callback function to execute when the event is triggered.
### Returns
- _Muuri_ - Returns the grid instance.
### Examples
```javascript
grid.on('layoutEnd', function (items) {
console.log(items);
});
```
```
--------------------------------
### Initialize Grid with CSS Selector for Items
Source: https://github.com/haltu/muuri/blob/master/README.md
Configure a Muuri grid to use a CSS selector to identify its items among the container's children.
```javascript
// Use selector.
var grid = new Muuri(elem, {
items: '.item',
});
```
--------------------------------
### Grid Methods
Source: https://github.com/haltu/muuri/blob/master/README.md
Provides a list of methods available on Muuri grid instances for managing items, layouts, and grid behavior.
```APIDOC
## Grid Methods
### Description
Provides a list of methods available on Muuri grid instances for managing items, layouts, and grid behavior.
### Methods
- **`getItem(element)`**: Returns the Muuri.Item instance associated with the given DOM element.
- **`getItems()`**: Returns an array of all Muuri.Item instances currently in the grid.
- **`refreshItems()`**: Refreshes the layout of all items in the grid. Useful after adding or removing items, or changing their content.
- **`send(item, grid, position)`**: Sends an item to another grid. Returns a Promise that resolves when the item has been successfully moved.
- **`sort(compareFn)`**: Sorts the grid items based on the provided comparison function. Returns a Promise that resolves when the sorting animation is complete.
- **`filter(ids)`**: Filters the grid items, showing only those whose IDs are present in the provided array. Returns a Promise that resolves when the filtering animation is complete.
- **`show(items, animate)`**: Shows the specified items. Returns a Promise that resolves when the showing animation is complete.
- **`hide(items, animate)`**: Hides the specified items. Returns a Promise that resolves when the hiding animation is complete.
- **`add(items)`**: Adds new items to the grid. Returns an array of the added Muuri.Item instances.
- **`remove(items)`**: Removes items from the grid. Returns a Promise that resolves when the removal animation is complete.
- **`destroy()`**: Destroys the Muuri instance, removing all event listeners and cleanup.
- **`on(event, listener)`**: Adds an event listener to the grid.
- **`off(event, listener)`**: Removes an event listener from the grid.
- **`once(event, listener)`**: Adds a one-time event listener to the grid.
- **` தரவு (key, value)`**: Sets a data attribute on the grid.
- **` தரவு (key)`**: Gets a data attribute from the grid.
```
--------------------------------
### grid.layout( [instant], [callback] )
Source: https://github.com/haltu/muuri/blob/master/README.md
Calculates item positions and moves items to their calculated positions. Adjusts grid dimensions and can be performed instantly or with a callback.
```APIDOC
## grid.layout( [instant], [callback] )
### Description
Calculates item positions and moves items to their calculated positions if they are not already correct. The grid's dimensions are also adjusted. This method can optionally perform the layout instantly and accept a callback function.
### Method
`grid.layout(instant, callback)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **instant** (_boolean_): Optional. If `true`, items are positioned instantly without animation. Defaults to `false`.
- **callback** (_function_): Optional. A function called after all items have finished positioning. Receives an array of items and a boolean indicating if the layout changed.
### Returns
- _Muuri_: Returns the grid instance.
### Request Example
```javascript
// Layout items.
grid.layout();
// Layout items instantly (without animations).
grid.layout(true);
// Layout all items and define a callback that will be called
// after all items have been animated to their positions.
grid.layout(function (items, hasLayoutChanged) {
// If hasLayoutChanged is `true` it means that there has been another layout
// call before this layout had time to finish positioning all the items.
console.log('layout done!');
});
```
```
--------------------------------
### grid.show( items, [options] )
Source: https://github.com/haltu/muuri/blob/master/README.md
Displays the targeted items in the grid. This method can optionally take an options object to control animation, layout synchronization, and callbacks.
```APIDOC
## grid.show( items, [options] )
### Description
Displays the targeted items in the grid. This method can optionally take an options object to control animation, layout synchronization, and callbacks.
### Method
`show`
### Parameters
#### Path Parameters
- **items** (array) - Required - An array of item instances.
#### Query Parameters
- **options** (object) - Optional - Configuration options for showing items.
- **instant** (boolean) - Optional - Should the items be shown instantly without any possible animation? Default: `false`.
- **syncWithLayout** (boolean) - Optional - Should we wait for the next layout's calculations to finish before starting the show animations? Default: `true`.
- **onFinish** (function) - Optional - A callback function that is called after the items are shown.
- **layout** (boolean / function / string) - Optional - Controls the layout call at the end of the method. Can be `false` to disable, a callback function, or `'instant'` for instant layout. Default: `true`.
### Request Example
```javascript
// Show items with animation (if any).
grid.show([itemA, itemB]);
// Show items instantly without animations.
grid.show([itemA, itemB], { instant: true });
// Show items with callback (and with animations if any).
grid.show([itemA, itemB], {
onFinish: function (items) {
console.log('items shown!');
},
});
```
### Response
#### Success Response
- **Muuri** - Returns the grid instance.
```
--------------------------------
### Listen for Layout End
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Triggered after the layout procedure has finished successfully. Use this to perform actions once all items have been positioned.
```javascript
grid.on('layoutEnd', function (items) {
console.log(items);
// For good measure you might want to filter out all the non-active items,
// because it's techniclly possible that some of the items are
// destroyed/hidden when we receive this event.
var activeItems = items.filter(function (item) {
return item.isActive();
});
});
```
--------------------------------
### grid.on(event, listener)
Source: https://github.com/haltu/muuri/blob/master/README.md
Binds an event listener to the grid instance. This allows you to react to various grid events.
```APIDOC
## grid.on(event, listener)
### Description
Binds an event listener to the grid instance. This allows you to react to various grid events.
### Method
(Not explicitly defined as HTTP)
### Endpoint
(Not applicable for SDK method)
### Parameters
- **event** (_string_) - The name of the event to listen for.
- **listener** (_function_) - The callback function to execute when the event is triggered.
### Returns
- _Muuri_ - Returns the grid instance.
### Request Example
```javascript
grid.on('layoutEnd', function (items) {
console.log(items);
});
```
```
--------------------------------
### Show Items Instantly
Source: https://github.com/haltu/muuri/blob/master/README.md
Shows items immediately without any animation. Useful for performance-critical updates or when animations are not desired.
```javascript
// Show items instantly without animations.
grid.show([itemA, itemB], { instant: true });
```
--------------------------------
### Enable Layout on Resize (Debounced)
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Set `layoutOnResize` to a number (milliseconds) to enable debounced layout triggering on window resize.
```javascript
var grid = new Muuri(elem, {
layoutOnResize: 200,
});
```
--------------------------------
### Show Items in Muuri Grid
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Use this snippet to display items in the grid. Options include showing items instantly, synchronizing with layout, and providing a callback.
```javascript
// Show items with animation (if any).
grid.show([itemA, itemB]);
// Show items instantly without animations.
grid.show([itemA, itemB], { instant: true });
// Show items with callback (and with animations if any).
grid.show([itemA, itemB], {
onFinish: function (items) {
console.log('items shown!');
},
});
```
--------------------------------
### Item Methods
Source: https://github.com/haltu/muuri/blob/master/README.md
Details the methods available on individual Muuri.Item instances for controlling their state and appearance.
```APIDOC
## Item Methods
### Description
Details the methods available on individual Muuri.Item instances for controlling their state and appearance.
### Methods
- **`getElement()`**: Returns the main DOM element of the item.
- **`getContent()`**: Returns the inner content element of the item.
- **`getWidth()`**: Returns the current width of the item.
- **`getHeight()`**: Returns the current height of the item.
- **`getGrid()`**: Returns the Muuri grid instance that the item belongs to.
- **`getId()`**: Returns the ID of the item.
- **`show(animate)`**: Shows the item. Returns a Promise that resolves when the showing animation is complete.
- **`hide(animate)`**: Hides the item. Returns a Promise that resolves when the hiding animation is complete.
- **`remove(animate)`**: Removes the item from the grid. Returns a Promise that resolves when the removal animation is complete.
- **`isShowing()`**: Returns `true` if the item is currently visible, `false` otherwise.
- **`isHiding()`**: Returns `true` if the item is currently being hidden, `false` otherwise.
- **`isShowingOrHiding()`**: Returns `true` if the item is currently in the process of showing or hiding, `false` otherwise.
- **`isPositioned()`**: Returns `true` if the item has been positioned, `false` otherwise.
- **`isSorted()`**: Returns `true` if the item is currently sorted, `false` otherwise.
- **`isFiltered()`**: Returns `true` if the item is currently filtered, `false` otherwise.
- **`isDragged()`**: Returns `true` if the item is currently being dragged, `false` otherwise.
```
--------------------------------
### Run Unit Tests with Specific Browsers
Source: https://github.com/haltu/muuri/blob/master/CONTRIBUTING.md
Executes unit tests for Muuri, allowing specification of browsers to test against. Requires `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` in an `.env` file.
```bash
npm run test --chrome --firefox --safari --edge
```
--------------------------------
### Format Code
Source: https://github.com/haltu/muuri/blob/master/CONTRIBUTING.md
Formats all files in the `src` directory using Prettier to maintain consistent code style.
```bash
npm run format
```
--------------------------------
### Customize Default Muuri Layout
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Configure the default layout algorithm with options like fillGaps, horizontal, alignRight, alignBottom, and rounding.
```javascript
var grid = new Muuri(elem, {
layout: {
fillGaps: true,
horizontal: true,
alignRight: true,
alignBottom: true,
rounding: true,
},
});
```
--------------------------------
### hideStart
Source: https://github.com/haltu/muuri/blob/master/README.md
Triggered just before items are hidden after `grid.hide()` is called.
```APIDOC
## event: hideStart
### Description
Triggered after `grid.hide()` is called, just before the items are hidden.
### Arguments
- **items** (array) - The items that are about to be hidden.
### Example
```javascript
grid.on('hideStart', function (items) {
console.log(items);
});
```
```
--------------------------------
### Muuri Constructor
Source: https://github.com/haltu/muuri/blob/master/docs/grid-constructor.md
The Muuri constructor function is used to create new grid instances. It accepts an element or a selector string for the grid container and an optional configuration object.
```APIDOC
## Muuri( element, [options] )
### Description
Instantiates a new Muuri grid.
### Parameters
#### Path Parameters
- **element** (element / string) - Required - The DOM element or a CSS selector string for the grid container.
- **options** (object) - Optional - An object containing configuration options for the grid.
### Request Example
```javascript
// Minimum configuration.
var gridA = new Muuri('.grid-a');
// Providing some options.
var gridB = new Muuri('.grid-b', {
items: '.item'
});
```
### Default Options
The default options can be accessed and modified via `Muuri.defaultOptions`.
```javascript
// Modifying default options
Muuri.defaultOptions.showDuration = 400;
Muuri.defaultOptions.dragSortPredicate.action = 'swap';
```
```
--------------------------------
### getElement
Source: https://github.com/haltu/muuri/blob/master/docs/grid-methods.md
Retrieves the main DOM element associated with the grid instance.
```APIDOC
## getElement
### Description
Get the grid element.
### Method
`grid.getElement()`
### Returns
- _element_ - The DOM element of the grid.
### Example
```javascript
var elem = grid.getElement();
```
```
--------------------------------
### Using Pointer as Scroll Handle
Source: https://github.com/haltu/muuri/blob/master/docs/grid-options.md
Demonstrates using the Muuri.AutoScroller.pointerHandle utility to define the scroll handle based on pointer position and size. This allows the scroll behavior to be tied to the cursor's proximity to the scrollable area.
```javascript
Muuri.AutoScroller.pointerHandle(pointerSize)
```
--------------------------------
### Show Items with Animation
Source: https://github.com/haltu/muuri/blob/master/README.md
Shows items with default animations. Use this when you want visual feedback during the item display.
```javascript
// Show items with animation (if any).
grid.show([itemA, itemB]);
```
--------------------------------
### Listen for beforeReceive Event
Source: https://github.com/haltu/muuri/blob/master/docs/grid-events.md
Logs the data object when an item is about to be received by a grid. Useful for inspecting or manipulating the incoming item.
```javascript
grid.on('beforeReceive', function (data) {
console.log(data);
});
```