Muuri

Infinite responsive, sortable, filterable and draggable layouts

README

Muuri is a JavaScript layout engine that allows you to build all kinds of layouts (no kidding!) and make them responsive, sortable, filterable, draggable and/or animated. Comparing to what's out there Muuri is a combination of Packery, Masonry, Isotope and Sortable. Wanna see it in action? Check out the demo on the website.
Features
- Fully customizable layout
- Asynchronous layout calculations in web workers
- Drag & drop (even between grids)
- Auto-scrolling during drag
- Nested grids
- Fast animations
- Filtering
- Sorting

Table of contents

- API

Motivation

You can build pretty amazing layouts without a single line of JavaScript these days. However, sometimes (rarely though) CSS just isn't enough, and that's where Muuri comes along. At it's very core Muuri is a _layout engine_ which is limited only by your imagination. You can seriously build _any_ kind of layout, asynchronously in web workers if you wish.
Custom layouts aside, you might need to sprinkle some flare (animation) and/or interactivity (filtering / sorting / drag & drop) on your layout (be it CSS or JS based). Stuff gets complex pretty fast and most of us probably reach for existing libraries to handle the complexity at that point. This is why most of these extra features are built into Muuri's core, so you don't have to go hunting for additional libraries or re-inventing the wheel for the nth time.
The long-term goal of Muuri is to provide a simple (and as low-level as possible) API for building amazing layouts with unmatched performance and _most_ of the complexity abstracted away.

Getting started

1. Get Muuri

Install via npm:
  1. ``` sh
  2. npm install muuri
  3. ```
Or download:
- muuri.js - for development (not minified, with comments).
- muuri.min.js - for production (minified, no comments).
Or link directly:
  1. ``` html
  2. <script src="https://cdn.jsdelivr.net/npm/muuri@0.9.5/dist/muuri.min.js"></script>
  3. ```

2. Get Web Animations Polyfill (if needed)

Muuri uses Web Animations to handle all the animations by default. If you need to use Muuri on a browser that does not support Web Animations you need to use a polyfill.
Install via npm:
  1. ``` sh
  2. npm install web-animations-js
  3. ```
Or download:
Or link directly:
  1. ``` html
  2. <script src="https://cdn.jsdelivr.net/npm/web-animations-js@2.3.2/web-animations.min.js"></script>
  3. ```

3. Add the markup

- Every grid must have a container element (referred as the _grid element_ from now on).
- Grid items must always consist of at least two elements. The outer element is used for positioning the item and the inner element (first direct child) is used for animating the item's visibility (show/hide methods). You can insert any markup you wish inside the inner item element.
- Note that the class names in the below example are not required by Muuri at all, they're just there for example's sake.
  1. ``` html
  2. <div class="grid">
  3.   <div class="item">
  4.     <div class="item-content">
  5.       
  6.       This can be anything.
  7.       
  8.     </div>
  9.   </div>
  10. <div class="item">
  11.     <div class="item-content">
  12.       
  13.       <div class="my-custom-content">
  14.         Yippee!
  15.       </div>
  16.       
  17.     </div>
  18.   </div>
  19. </div>
  20. ```

4. Add the styles

- The grid element must be "positioned" meaning that it's CSS position property must be set to _relative_, _absolute_ or _fixed_. Also note that Muuri automatically resizes the grid element's width/height depending on the area the items cover and the layout algorithm configuration.
- The item elements must have their CSS position set to _absolute_.
- The item elements must not have any CSS transitions or animations applied to them, because they might conflict with Muuri's internal animation engine. However, the grid element can have transitions applied to it if you want it to animate when it's size changes after the layout operation.
- You can control the gaps between the items by giving some margin to the item elements.
- One last thing. Never ever set overflow: auto; or overflow: scroll; to the grid element. Muuri's calculation logic does not account for that and you _will_ see some item jumps when dragging starts. Always use a wrapper element for the grid element where you set the auto/scroll overflow values.
  1. ```css
  2. .grid {
  3.   position: relative;
  4. }
  5. .item {
  6.   display: block;
  7.   position: absolute;
  8.   width: 100px;
  9.   height: 100px;
  10.   margin: 5px;
  11.   z-index: 1;
  12.   background: #000;
  13.   color: #fff;
  14. }
  15. .item.muuri-item-dragging {
  16.   z-index: 3;
  17. }
  18. .item.muuri-item-releasing {
  19.   z-index: 2;
  20. }
  21. .item.muuri-item-hidden {
  22.   z-index: 0;
  23. }
  24. .item-content {
  25.   position: relative;
  26.   width: 100%;
  27.   height: 100%;
  28. }
  29. ```

5. Fire it up

The bare minimum configuration is demonstrated below. You must always provide the grid element (or a selector so Muuri can fetch the element for you), everything else is optional.
  1. ``` js
  2. var grid = new Muuri('.grid');
  3. ```
You can view this little tutorial demo here. After that you might want to check some other demos as well.

API

Grid constructor

Muuri is a constructor function and should be always instantiated with the new keyword. For the sake of clarity, we refer to a Muuri instance as _grid_ throughout the documentation.
Syntax
Muuri( element, [options] )
Parameters
- element  —  _element_ / _string_
  - Default value: null.
  - You can provide the element directly or use a selector (string) which uses querySelector() internally.
- options  —  _object_
  - Optional. Check out the detailed options reference.
Default options
The default options are stored in Muuri.defaultOptions object, which in it's default state contains the following configuration:
  1. ``` js
  2. {
  3.   // Initial item elements
  4.   items: '*',
  5.   // Default show animation
  6.   showDuration: 300,
  7.   showEasing: 'ease',
  8.   // Default hide animation
  9.   hideDuration: 300,
  10.   hideEasing: 'ease',
  11.   // Item's visible/hidden state styles
  12.   visibleStyles: {
  13.     opacity: '1',
  14.     transform: 'scale(1)'
  15.   },
  16.   hiddenStyles: {
  17.     opacity: '0',
  18.     transform: 'scale(0.5)'
  19.   },
  20.   // Layout
  21.   layout: {
  22.     fillGaps: false,
  23.     horizontal: false,
  24.     alignRight: false,
  25.     alignBottom: false,
  26.     rounding: false
  27.   },
  28.   layoutOnResize: 150,
  29.   layoutOnInit: true,
  30.   layoutDuration: 300,
  31.   layoutEasing: 'ease',
  32.   // Sorting
  33.   sortData: null,
  34.   // Drag & Drop
  35.   dragEnabled: false,
  36.   dragContainer: null,
  37.   dragHandle: null,
  38.   dragStartPredicate: {
  39.     distance: 0,
  40.     delay: 0
  41.   },
  42.   dragAxis: 'xy',
  43.   dragSort: true,
  44.   dragSortHeuristics: {
  45.     sortInterval: 100,
  46.     minDragDistance: 10,
  47.     minBounceBackAngle: 1
  48.   },
  49.   dragSortPredicate: {
  50.     threshold: 50,
  51.     action: 'move',
  52.     migrateAction: 'move'
  53.   },
  54.   dragRelease: {
  55.     duration: 300,
  56.     easing: 'ease',
  57.     useDragContainer: true
  58.   },
  59.   dragCssProps: {
  60.     touchAction: 'none',
  61.     userSelect: 'none',
  62.     userDrag: 'none',
  63.     tapHighlightColor: 'rgba(0, 0, 0, 0)',
  64.     touchCallout: 'none',
  65.     contentZooming: 'none'
  66.   },
  67.   dragPlaceholder: {
  68.     enabled: false,
  69.     createElement: null,
  70.     onCreate: null,
  71.     onRemove: null
  72.   },
  73.   dragAutoScroll: {
  74.     targets: [],
  75.     handle: null,
  76.     threshold: 50,
  77.     safeZone: 0.2,
  78.     speed: Muuri.AutoScroller.smoothSpeed(1000, 2000, 2500),
  79.     sortDuringScroll: true,
  80.     smoothStop: false,
  81.     onStart: null,
  82.     onStop: null
  83.   },
  84.   // Classnames
  85.   containerClass: 'muuri',
  86.   itemClass: 'muuri-item',
  87.   itemVisibleClass: 'muuri-item-shown',
  88.   itemHiddenClass: 'muuri-item-hidden',
  89.   itemPositioningClass: 'muuri-item-positioning',
  90.   itemDraggingClass: 'muuri-item-dragging',
  91.   itemReleasingClass: 'muuri-item-releasing',
  92.   itemPlaceholderClass: 'muuri-item-placeholder'
  93. }
  94. ```
You can modify the default options easily:
  1. ``` js
  2. Muuri.defaultOptions.showDuration = 400;
  3. Muuri.defaultOptions.dragSortPredicate.action = 'swap';
  4. ```
This is how you would use the options:
  1. ``` js
  2. // Minimum configuration.
  3. var gridA = new Muuri('.grid-a');
  4. // Providing some options.
  5. var gridB = new Muuri('.grid-b', {
  6.   items: '.item',
  7. });
  8. ```

Grid options

option: items

The initial item elements, which should be children of the grid element. All elements that are not children of the grid element (e.g. if they are not in the DOM yet) will be appended to the grid element. You can provide an array of elements, NodeList, HTMLCollection or a selector (string). If you provide a selector Muuri uses it to filter the current child elements of the container element and sets them as initial items. By default all current child elements of the provided grid element are used as initial items.
- Default value: '*'.
- Accepted types: array (of elements), NodeList, HTMLCollection, string, null.
Examples
  1. ``` js
  2. // Use specific items.
  3. var grid = new Muuri(elem, {
  4.   items: [elemA, elemB, elemC],
  5. });
  6. // Use node list.
  7. var grid = new Muuri(elem, {
  8.   items: elem.querySelectorAll('.item'),
  9. });
  10. // Use selector.
  11. var grid = new Muuri(elem, {
  12.   items: '.item',
  13. });
  14. ```

option: showDuration

Show animation duration in milliseconds. Set to 0 to disable show animation.
- Default value: 300.
- Accepted types: number.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   showDuration: 600,
  4. });
  5. ```

option: showEasing

Show animation easing. Accepts any valid Animation easing value.
- Default value: 'ease'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   showEasing: 'cubic-bezier(0.215, 0.61, 0.355, 1)',
  4. });
  5. ```

option: hideDuration

Hide animation duration in milliseconds. Set to 0 to disable hide animation.
- Default value: 300.
- Accepted types: number.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   hideDuration: 600,
  4. });
  5. ```

option: hideEasing

Hide animation easing. Accepts any valid Animation easing value.
- Default value: 'ease'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   hideEasing: 'cubic-bezier(0.215, 0.61, 0.355, 1)',
  4. });
  5. ```

option: visibleStyles

The styles that will be applied to all visible items. These styles are also used for the show/hide animations which means that you have to have the same style properties in visibleStyles and hiddenStyles options. Be sure to define all style properties camel cased and without vendor prefixes (Muuri prefixes the properties automatically where needed).
- Default value:
  1. ``` js
  2.   {
  3.     opacity: 1,
  4.     transform: 'scale(1)'
  5.   }
  6. ```
- Accepted types: object.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   visibleStyles: {
  4.     opacity: 1,
  5.     transform: 'rotate(45deg)',
  6.   },
  7.   hiddenStyles: {
  8.     opacity: 0,
  9.     transform: 'rotate(-45deg)',
  10.   },
  11. });
  12. ```

option: hiddenStyles

The styles that will be applied to all hidden items. These styles are also used for the show/hide animations which means that you have to have the same style properties in visibleStyles and hiddenStyles options. Be sure to define all style properties camel cased and without vendor prefixes (Muuri prefixes the properties automatically where needed).
- Default value:
  1. ``` js
  2.   {
  3.     opacity: 0,
  4.     transform: 'scale(0.5)'
  5.   }
  6. ```
- Accepted types: object.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   visibleStyles: {
  4.     opacity: 1,
  5.     transform: 'rotate(45deg)',
  6.   },
  7.   hiddenStyles: {
  8.     opacity: 0,
  9.     transform: 'rotate(-45deg)',
  10.   },
  11. });
  12. ```

option: layout

Define how the items will be positioned. Muuri ships with a configurable layout algorithm which is used by default. It's pretty flexible and suitable for most common situations (lists, grids and even bin packed grids). If that does not fit the bill you can always provide your own layout algorithm (it's not as scary as it sounds).
Muuri supports calculating the layout both synchronously and asynchronously. By default (if you use the default layout algorithm) Muuri will use two shared web workers to compute the layouts asynchronously. In browsers that do not support web workers Muuri will fallback to synchronous layout calculations.
- Default value:
  1. ``` js
  2.   {
  3.     fillGaps: false,
  4.     horizontal: false,
  5.     alignRight: false,
  6.     alignBottom: false,
  7.     rounding: false
  8.   }
  9. ```
- Accepted types: function, object.
Provide an _object_ to configure the default layout algorithm with the following properties
- fillGaps  —  _boolean_
  - Default value: false.
  - When true the algorithm goes through every item in order and places each item to the first available free slot, even if the slot happens to be visually _before_ the previous element's slot. Practically this means that the items might not end up visually in order, but there will be less gaps in the grid.
- horizontal  —  _boolean_
  - Default value: false.
  - When true the grid works in landscape mode (grid expands to the right). Use for horizontally scrolling sites. When false the grid works in "portrait" mode and expands downwards.
- alignRight  —  _boolean_
  - Default value: false.
  - When true the items are aligned from right to left.
- alignBottom  —  _boolean_
  - Default value: false.
  - When true the items are aligned from the bottom up.
- rounding  —  _boolean_
  - Default value: false.
  - When true the item dimensions are rounded to a precision of two decimals for the duration of layout calculations. This procedure stabilizes the layout calculations quite a lot, but also causes a hit on performance. Use only if you see your layout behaving badly, which might happen sometimes (hopefully never) when using relative dimension values.
Provide a _function_ to use a custom layout algorithm
When you provide a custom layout function Muuri calls it whenever calculation of layout is necessary. Before calling the layout function Muuri always calculates the current width and height of the grid element and also creates an array of all the items that are part of the layout currently (all _active_ items).
The layout function always receives the following arguments:
- grid  —  _Muuri_
  - The grid instance that requested the layout.
- layoutId  —  _number_
  - Automatically generated unique id for the layout which is used to keep track of the layout requests and to make sure that the correct layout gets applied at correct time.
- items  —  _array_
  - Array of Muuri.Item instances. A new array instance is created for each layout so there's no harm in manipulating this if you need to (or using it as is for the layout data object).
- width  —  _number_
  - Current width (in pixels) of the grid element (excluding borders, but including padding).
- height  —  _number_
  - Current height (in pixels) of the grid element (excluding borders, but including padding).
- callback  —  _function_
  - When the layout is calculated and ready to be applied you need to call this callback function and provide a _layout object_ as it's argument. Note that if another layout is requesteded while the current layout is still being calculated (asynchronously) this layout will be ignored.
If the layout function's calculations are asynchronous you can optionally return a cancel function, which Muuri will call if there is a new layout request before the current layout has finished it's calculations.
The layout object, which needs to be provided to the callback, must include the following properties.
- id  —  _number_
  - The layout's unique id (must be the layoutId provided by Muuri).
- items  —  _array_
  - Array of the active item instances that are part of the layout. You can pass the same items array here which is provided by Muuri (in case you haven't mutated it). This array items must be identical to the array of items provided by Muuri.
- slots  —  _array_
  - Array of the item positions (numbers). E.g. if the items were [a, b] this should be [aLeft, aTop, bLeft, bTop]. You have to calculate the left and top position for each item in the provided _items_ array in the same order the items are provided.
- styles  —  _object / null_
  - Here you can optionally define all the layout related CSS styles that should be applied to the grid element _just_ before the layoutStart event is emitted. E.g. {width: '100%', height: '200px', minWidth: '200px'}.
  - It's important to keep in mind here that if the grid element's box-sizing CSS property is set to border-box the element's borders are included in the dimensions. E.g. if you set {width: '100px', width: '100px'} here and the element has a 5px border and box-sizing is set to border-box, then the _layout's_ effective width and height (as perceived by Muuri) will be 90px. So remember to take that into account and add the borders to the dimensions when necessary. If this sounds complicated then just don't set borders directly to the grid element or make sure that grid element's box-sizing is set to content-box (which is the default value).
Note that you can add additional properties to the layout object if you wish, e.g. the default layout algorithm also stores the layout's width and height (in pixels) to the layout object.
Examples
  1. ``` js
  2. // Customize the default layout algorithm.
  3. var grid = new Muuri(elem, {
  4.   layout: {
  5.     fillGaps: true,
  6.     horizontal: true,
  7.     alignRight: true,
  8.     alignBottom: true,
  9.     rounding: true,
  10.   },
  11. });
  12. ```
  1. ``` js
  2. // Build your own layout algorithm.
  3. var grid = new Muuri(elem, {
  4.   layout: function (grid, layoutId, items, width, height, callback) {
  5.     var layout = {
  6.       id: layoutId,
  7.       items: items,
  8.       slots: [],
  9.       styles: {},
  10.     };
  11.     // Calculate the slots asynchronously. Note that the timeout is here only
  12.     // as an example and does not help at all in the calculations. You should
  13.     // offload the calculations to web workers if you want real benefits.
  14.     // Also note that doing asynchronous layout is completely optional and you
  15.     // can call the callback function synchronously also.
  16.     var timerId = window.setTimeout(function () {
  17.       var item,
  18.         m,
  19.         x = 0,
  20.         y = 0,
  21.         w = 0,
  22.         h = 0;
  23.       for (var i = 0; i < items.length; i++) {
  24.         item = items[i];
  25.         x += w;
  26.         y += h;
  27.         m = item.getMargin();
  28.         w = item.getWidth() + m.left + m.right;
  29.         h = item.getHeight() + m.top + m.bottom;
  30.         layout.slots.push(x, y);
  31.       }
  32.       w += x;
  33.       h += y;
  34.       // Set the CSS styles that should be applied to the grid element.
  35.       layout.styles.width = w + 'px';
  36.       layout.styles.height = h + 'px';
  37.       // When the layout is fully computed let's call the callback function and
  38.       // provide the layout object as it's argument.
  39.       callback(layout);
  40.     }, 200);
  41.     // If you are doing an async layout you _can_ (if you want to) return a
  42.     // function that cancels this specific layout calculations if it's still
  43.     // processing/queueing when the next layout is requested.
  44.     return function () {
  45.       window.clearTimeout(timerId);
  46.     };
  47.   },
  48. });
  49. ```

option: layoutOnResize

Should Muuri automatically trigger layout method on window resize? Set to false to disable. When a number or true is provided Muuri will automatically position the items every time window is resized. The provided number (true is transformed to 0) equals to the amount of time (in milliseconds) that is waited before items are positioned after each window resize event.
- Default value: 150.
- Accepted types: boolean, number.
Examples
  1. ``` js
  2. // No layout on resize.
  3. var grid = new Muuri(elem, {
  4.   layoutOnResize: false,
  5. });
  6. ```
  1. ``` js
  2. // Layout on resize (instantly).
  3. var grid = new Muuri(elem, {
  4.   layoutOnResize: true,
  5. });
  6. ```
  1. ``` js
  2. // Layout on resize (with 200ms debounce).
  3. var grid = new Muuri(elem, {
  4.   layoutOnResize: 200,
  5. });
  6. ```

option: layoutOnInit

Should Muuri trigger layout method automatically on init?
- Default value: true.
- Accepted types: boolean.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   layoutOnInit: false,
  4. });
  5. ```

option: layoutDuration

The duration for item's layout animation in milliseconds. Set to 0 to disable.
- Default value: 300.
- Accepted types: number.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   layoutDuration: 600,
  4. });
  5. ```

option: layoutEasing

The easing for item's layout animation. Accepts any valid Animation easing value.
- Default value: 'ease'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   layoutEasing: 'cubic-bezier(0.215, 0.61, 0.355, 1)',
  4. });
  5. ```

option: sortData

The sort data getter functions. Provide an object where the key is the name of the sortable attribute and the function returns a value (from the item) by which the items can be sorted.
- Default value: null.
- Accepted types: object, null.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   sortData: {
  4.     foo: function (item, element) {
  5.       return parseFloat(element.getAttribute('data-foo'));
  6.     },
  7.     bar: function (item, element) {
  8.       return element.getAttribute('data-bar').toUpperCase();
  9.     },
  10.   },
  11. });
  12. // Refresh sort data whenever an item's data-foo or data-bar changes
  13. grid.refreshSortData();
  14. // Sort the grid by foo and bar.
  15. grid.sort('foo bar');
  16. ```

option: dragEnabled

Should items be draggable?
- Default value: false.
- Accepted types: boolean.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   dragEnabled: true,
  4. });
  5. ```

option: dragContainer

The element the dragged item should be appended to for the duration of the drag. If set to null (which is also the default value) the grid element will be used.
- Default value: null.
- Accepted types: element, null.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   dragContainer: document.body,
  4. });
  5. ```

option: dragHandle

The element within the item element that should be used as the drag handle. This should be a CSS selector which will be fed to element.querySelector() as is to obtain the handle element when the item is instantiated. If no valid element is found or if this is null Muuri will use the item element as the handle.
- Default value: null.
- Accepted types: string, null.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   dragHandle: '.handle',
  4. });
  5. ```

option: dragStartPredicate

A function that determines when the item should start moving when the item is being dragged. By default uses the built-in start predicate which has some configurable options.
- Default value:
  1. ``` js
  2.   {
  3.     distance: 0,
  4.     delay: 0
  5.   }
  6. ```
- Accepted types: function, object.
If an object is provided the default start predicate handler will be used. You can define the following properties:
- distance  —  _number_
  - Default value: 0.
  - How many pixels the user must drag before the drag procedure starts and the item starts moving.
- delay  —  _number_
  - Default value: 0.
  - How long (in milliseconds) the user must drag before the dragging starts.
If you provide a function you can customize the drag start logic as you please. When the user starts to drag an item this predicate function will be called until you return true or false. If you return true the item will begin to move whenever the item is dragged. If you return false the item will not be moved at all. Note that after you have returned true or false this function will not be called until the item is released and dragged again.
The predicate function receives two arguments:
- item  —  _Muuri.Item_
  - The item that's being dragged.
- event  —  _object_
  - Muuri.Dragger event data.
Examples
  1. ``` js
  2. // Configure the default predicate
  3. var grid = new Muuri(elem, {
  4.   dragStartPredicate: {
  5.     distance: 10,
  6.     delay: 100,
  7.   },
  8. });
  9. ```
  1. ``` js
  2. // Provide your own predicate
  3. var grid = new Muuri(elem, {
  4.   dragStartPredicate: function (item, e) {
  5.     // Start moving the item after the item has been dragged for one second.
  6.     if (e.deltaTime > 1000) {
  7.       return true;
  8.     }
  9.   },
  10. });
  11. ```
  1. ``` js
  2. // Pro tip: provide your own predicate and fall back to the default predicate.
  3. var grid = new Muuri(elem, {
  4.   dragStartPredicate: function (item, e) {
  5.     // If this is final event in the drag process, let's prepare the predicate
  6.     // for the next round (do some resetting/teardown). The default predicate
  7.     // always needs to be called during the final event if there's a chance it
  8.     // has been triggered during the drag process because it does some necessary
  9.     // state resetting.
  10.     if (e.isFinal) {
  11.       Muuri.ItemDrag.defaultStartPredicate(item, e);
  12.       return;
  13.     }
  14.     // Prevent first item from being dragged.
  15.     if (grid.getItems()[0] === item) {
  16.       return false;
  17.     }
  18.     // For other items use the default drag start predicate.
  19.     return Muuri.ItemDrag.defaultStartPredicate(item, e);
  20.   },
  21. });
  22. ```

option: dragAxis

Force items to be moved only vertically or horizontally when dragged. Set to 'x' for horizontal movement and to 'y' for vertical movement. By default items can be dragged both vertically and horizontally.
- Default value: 'xy'.
- Accepted types: string.
- Allowed values: 'x', 'y', 'xy'.
Examples
  1. ``` js
  2. // Move items only horizontally when dragged.
  3. var grid = new Muuri(elem, {
  4.   dragAxis: 'x',
  5. });
  6. ```
  1. ``` js
  2. // Move items only vertically when dragged.
  3. var grid = new Muuri(elem, {
  4.   dragAxis: 'y',
  5. });
  6. ```

option: dragSort

Should the items be sorted during drag? A simple boolean will do just fine here.
Alternatively you can do some advanced stuff and control within which grids a specific item can be sorted and dragged into. To do that you need to provide a function which receives the dragged item as its first argument and should return an array of grid instances. An important thing to note here is that you need to return _all_ the grid instances you want the dragged item to sort within, even the current grid instance. If you return an empty array the dragged item will not cause sorting at all.
- Default value: true.
- Accepted types: boolean, function.
Examples
  1. ``` js
  2. // Disable drag sorting.
  3. var grid = new Muuri(elem, {
  4.   dragSort: false,
  5. });
  6. ```
  1. ``` js
  2. // Multigrid drag sorting.
  3. var gridA = new Muuri(elemA, { dragSort: getAllGrids });
  4. var gridB = new Muuri(elemB, { dragSort: getAllGrids });
  5. var gridC = new Muuri(elemC, { dragSort: getAllGrids });
  6. function getAllGrids(item) {
  7.   return [gridA, gridB, gridC];
  8. }
  9. ```

option: dragSortHeuristics

Defines various heuristics so that sorting during drag would be smoother and faster.
- Default value:
  1. ``` js
  2.   {
  3.     sortInterval: 100,
  4.     minDragDistance: 10,
  5.     minBounceBackAngle: 1
  6.   }
  7. ```
- Accepted types: object.
You can define the following properties:
- sortInterval  —  _number_
  - Default value: 100.
  - Defines the amount of time the dragged item must be still before dragSortPredicate function is called.
- minDragDistance  —  _number_
  - Default value: 10.
  - Defines how much (in pixels) the item must be dragged before dragSortPredicate can be called.
- minBounceBackAngle  —  _number_
  - Default value: 1.
  - Defines the minimum angle (in radians) of the delta vector between the last movement vector and the current movement vector that is required for the dragged item to be allowed to be sorted to it's previous index. The problem this heuristic is trying to solve is the scenario where you drag an item over a much bigger item and the bigger item moves, but it's still overlapping the dragged item after repositioning. Now when you move the dragged item again another sort is triggered and the bigger item moves back to it's previous position. This bouncing back and forth can go on for quite a while and it looks quite erratic. The fix we do here is that, by default, we disallow an item to be moved back to it's previous position, unless it's drag direction changes enough. And what is enough? That's what you can define here. Note that this option works in tandem with minDragDistance and needs it to be set to 3 at minimum to be enabled at all.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   dragEnabled: true,
  4.   dragSortHeuristics: {
  5.     sortInterval: 10,
  6.     minDragDistance: 5,
  7.     minBounceBackAngle: Math.PI / 2,
  8.   },
  9. });
  10. ```
  1. ``` js
  2. // Pro tip: If you want drag sorting happening only on release set a really
  3. // long sortInterval. A bit of a hack, but works.
  4. var grid = new Muuri(elem, {
  5.   dragEnabled: true,
  6.   dragSortHeuristics: {
  7.     sortInterval: 3600000, // 1 hour
  8.   },
  9. });
  10. ```

option: dragSortPredicate

Defines the logic for the sort procedure during dragging an item.
- Default value:
  1. ``` js
  2.   {
  3.     threshold: 50,
  4.     action: 'move',
  5.     migrateAction: 'move'
  6.   }
  7. ```
- Accepted types: function, object.
If an object is provided the default sort predicate handler will be used. You can define the following properties:
- threshold  —  _number_
  - Default value: 50.
  - Allowed values: 1 - 100.
  - How many percent the intersection area between the dragged item and the compared item should be from the maximum potential intersection area between the items before sorting is triggered.
- action  —  _string_
  - Default value: 'move'.
  - Allowed values: 'move', 'swap'.
  - Should the dragged item be _moved_ to the new position or should it _swap_ places with the item it overlaps when the drag occurs within the same grid?
- migrateAction  —  _string_
  - Default value: 'move'.
  - Allowed values: 'move', 'swap'.
  - Should the dragged item be _moved_ to the new position or should it _swap_ places with the item it overlaps when the dragged item is moved to another grid?
Alternatively you can provide your own callback function where you can define your own custom sort logic. The callback function receives two arguments:
- item  —  _Muuri.Item_
  - The item that's being dragged.
- event  —  _object_
  - Muuri.Dragger event data.
The callback should return a _falsy_ value if sorting should not occur. If, however, sorting should occur the callback should return an object containing the following properties:
- index  —  _number_
  - The index where the item should be moved to.
- grid  —  _Muuri_
  - The grid where the item should be moved to.
  - Defaults to the item's current grid.
  - Optional.
- action  —  _string_
  - The movement method.
  - Default value: 'move'.
  - Allowed values: 'move' or 'swap'.
  - Optional.
Examples
  1. ``` js
  2. // Customize the default predicate.
  3. var grid = new Muuri(elem, {
  4.   dragSortPredicate: {
  5.     threshold: 90,
  6.     action: 'swap',
  7.   },
  8. });
  9. ```
  1. ``` js
  2. // Provide your own predicate.
  3. var grid = new Muuri(elem, {
  4.   dragSortPredicate: function (item, e) {
  5.     if (e.deltaTime < 1000) return false;
  6.     return {
  7.       index: Math.round(e.deltaTime / 1000) % 2 === 0 ? -1 : 0,
  8.       action: 'swap',
  9.     };
  10.   },
  11. });
  12. ```
  1. ``` js
  2. // Pro tip: use the default predicate as fallback in your custom predicate.
  3. var grid = new Muuri(elem, {
  4.   dragSortPredicate: function (item, e) {
  5.     if (item.classList.contains('no-sort')) return false;
  6.     return Muuri.ItemDrag.defaultSortPredicate(item, {
  7.       action: 'swap',
  8.       threshold: 75,
  9.     });
  10.   },
  11. });
  12. ```

option: dragRelease

- Default value:
  1. ``` js
  2.   {
  3.     duration: 300,
  4.     easing: 'ease',
  5.     useDragContainer: true
  6.   }
  7. ```
- Accepted types: object.
You can define the following properties:
- duration  —  _number_
  - Default value: 300.
  - The duration for item's drag release animation. Set to 0 to disable.
- easing  —  _string_
  - Default value: 'ease'.
  - The easing for item's drag release animation. Accepts any valid Animation easing value.
- useDragContainer  —  _boolean_
  - Default value: true.
  - If true the item element will remain within the dragContainer for the duration of the release process. Otherwise the item element will be inserted within the grid element (if not already inside it) at the beginning of the release process.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   dragRelease: {
  4.     duration: 600,
  5.     easing: 'ease-out',
  6.     useDragContainer: false,
  7.   },
  8. });
  9. ```

option: dragCssProps

Drag specific CSS properties that Muuri sets to the draggable item elements. Muuri automatically prefixes the properties before applying them to the element. touchAction property is required to be always defined, but the other properties are optional and can be omitted by setting their value to an empty string if you want to e.g. define them via CSS only.
- Default value:
  1. ``` js
  2.   {
  3.     touchAction: 'none',
  4.     userSelect: 'none',
  5.     userDrag: 'none',
  6.     tapHighlightColor: 'rgba(0, 0, 0, 0)',
  7.     touchCallout: 'none',
  8.     contentZooming: 'none'
  9.   }
  10. ```
- Accepted types: object.
You can define the following properties:
- touchAction  —  _string_
  - Default value: 'none'.
  - https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action
- userSelect  —  _string_
  - Default value: 'none'.
  - https://developer.mozilla.org/en-US/docs/Web/CSS/user-select
  - Optional.
- userDrag  —  _string_
  - Default value: 'none'.
  - http://help.dottoro.com/lcbixvwm.php
  - Optional.
- tapHighlightColor  —  _string_
  - Default value: 'rgba(0, 0, 0, 0)'.
  - https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-tap-highlight-color
  - Optional.
- touchCallout  —  _string_
  - Default value: 'none'.
  - https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout
  - Optional.
- contentZooming  —  _string_
  - Default value: 'none'.
  - https://developer.mozilla.org/en-US/docs/Web/CSS/-ms-content-zooming
  - Optional.
Examples
  1. ``` js
  2. // Only set the required touch-action CSS property via the options if you for
  3. // example want to set the other props via CSS instead.
  4. var grid = new Muuri(elem, {
  5.   dragEnabled: true,
  6.   dragCssProps: {
  7.     touchAction: 'pan-y',
  8.     userSelect: '',
  9.     userDrag: '',
  10.     tapHighlightColor: '',
  11.     touchCallout: '',
  12.     contentZooming: '',
  13.   },
  14. });
  15. ```

option: dragPlaceholder

If you want a placeholder item to appear for the duration of an item's drag & drop procedure you can enable and configure it here. The placeholder animation duration is fetched from the grid's layoutDuration option and easing from the grid's layoutEasing option. Note that a special placeholder class is given to all drag placeholders and is customizable via itemPlaceholderClass option.
- Default value:
  1. ``` js
  2.   {
  3.     enabled: false,
  4.     createElement: null,
  5.     onCreate: null,
  6.     onRemove: null
  7.   }
  8. ```
- Accepted types: object.
You can define the following properties:
- enabled  —  _boolean_
  - Default value: false.
  - Is the placeholder enabled?
- createElement  —  _function / null_
  - Default value: null.
  - If defined, this method will be used to create the DOM element that is used for the placeholder. By default a new div element is created when a placeholder is summoned.
- onCreate  —  _function / null_
  - Default value: null.
  - An optional callback that will be called after a placeholder is created for an item.
- onRemove  —  _function / null_
  - Default value: null.
  - An optional callback that will be called after a placeholder is removed from the grid.
Examples
  1. ``` js
  2. // This example showcases how to pool placeholder elements
  3. // for better performance and memory efficiency.
  4. var phPool = [];
  5. var phElem = document.createElement('div');
  6. var grid = new Muuri(elem, {
  7.   dragEnabled: true,
  8.   dragPlaceholder: {
  9.     enabled: true,
  10.     createElement(item) {
  11.       return phPool.pop() || phElem.cloneNode();
  12.     },
  13.     onCreate(item, element) {
  14.       // If you want to do something after the
  15.       // placeholder is fully created, here's
  16.       // the place to do it.
  17.     },
  18.     onRemove(item, element) {
  19.       phPool.push(element);
  20.     },
  21.   },
  22. });
  23. ```

option: dragAutoScroll

If you want to trigger scrolling on any element during dragging you can enable and configure it here. By default this feature is disabled. When you use this feature it is _highly_ recommended that you create a fixed positioned element right under document.body and use that as the dragContainer for all the dragged items. If you don't do this and a dragged item's parent is auto-scrolled, the dragged item will potentially grow the scrolled element's scroll area to infinity unintentionally.
- Default value:
  1. ``` js
  2.   {
  3.     targets: [],
  4.     handle: null,
  5.     threshold: 50,
  6.     safeZone: 0.2,
  7.     speed: Muuri.AutoScroller.smoothSpeed(1000, 2000, 2500),
  8.     sortDuringScroll: true,
  9.     smoothStop: false,
  10.     onStart: null,
  11.     onStop: null
  12.   }
  13. ```
- Accepted types: object.
You can define the following properties:
- targets  —  _array / function_
  - Default value: [].
  - Define the DOM elements that should be scrolled during drag. As long as this array is empty there will be no scrolling during drag. To keep it simple you can just provide an array of elements here, in which case Muuri attempts to scroll the elements both vertically and horizontally when possible. If you want more fine-grained control, e.g. scroll an element only on specific axis or prioritize some element over another (handy for cases when there are overlapping elements), you can provide an array of scroll targets (objects). Finally, you can also provide a function which receives the dragged item instance as it's argument and which should return an array of scroll targets (elements and/or objects). This way you can provide different configurations for different items.
  - scrollTarget  —  _object_
    - element  —  _element_ / _window_
      - The DOM element to scroll.
      - Required.
    - axis  —  _number_
      - Optional. Defaults to scrolling both axes: Muuri.AutoScroller.AXIS_X | Muuri.AutoScroller.AXIS_Y.
      - To scroll only x-axis: Muuri.AutoScroller.AXIS_X.
      - To scroll only y-axis: Muuri.AutoScroller.AXIS_Y.
    - priority  —  _number_
      - Default: 0.
      - A dragged item can only scroll one element horizontally and one element vertically simultaneously. This is an artificial limit to fend off unnecesary complexity, and to avoid awkward situations. In the case where the dragged item overlaps multiple scrollable elements simultaneously and exceeds their scroll thresholds we pick the one that the dragged item overlaps most. However, that's not always the best choice. This is where priority comes in. Here you can manually tell Muuri which element to prefer over another in these scenarios. The element with highest priority _always_ wins the fight, in matches with equal priority we determine the winner by the amount of overlap.
      - Optional.
    - threshold  —  _number / null_
      - Default: null.
      - If defined (a number is provided), this value will override the default threshold for _this scroll target_. Otherwise the default threshold will be used.
      - Optional.
- handle  —  _function / null_
  - Default value: null.
  - This property defines size and position of the handle (the rectangle that is compared against the scroll element's threshold). By default (when null) the dragged element's dimensions and offsets are used. However, you can provide a function which should return an object containing the handle's client offsets in pixels (left and top) and dimensions in pixels (width and height). The function receives the following arguments:
    - item  —  _Muuri.Item_
    - itemClientX  —  _number_
    - itemClientY  —  _number_
    - itemWidth  —  _number_
    - itemHeight  —  _number_
    - pointerClientX  —  _number_
    - pointerClientY  —  _number_
  - Tip: Use Muuri.AutoScroller.pointerHandle(pointerSize) utility method if you want to use the pointer (instead of the element) as the handle.
- threshold  —  _number_
  - Default value: 50.
  - Defines the distance (in pixels) from the edge of the scrollable element when scrolling should start, in pixels. If this value is 0 the scrolling will start when the dragged element reaches the scrollable element's edge. Do note that Muuri dynamically adjusts the scroll element's _edge_ for the calculations (when needed).
- safeZone  —  _number_
  - Default value: 0.2.
  - Defines the size of the minimum "safe zone" space, an area in the center of the scrollable element that will be guaranteed not trigger scrolling regardless of threshold size and the dragged item's size. This value is a percentage of the scrollable element's size (width and/or height depending on the scroll axes), and should be something between 0 and 1. So in practice, if you set this to e.g 0.5 the safe zone would be 50% of the scrollable element's width and/or height.
- speed  —  _number / function_
  - Default value: Muuri.AutoScroller.smoothSpeed(1000, 2000, 2500).
  - Defines the scrolling speed in pixels per second. You can provide either static speed with a number or dynamic speed with a function. The function is called before every scroll operation and should return the speed (number, pixels per second) for the next scroll operation. The function receives three arguments:
    - item  —  _Muuri.Item_
      - The dragged Muuri.Item instance.
    - scrollElement  —  _element_ / _window_
      - The scrolled element.
    - data  —  _object_
      - data.direction  —  _number_
        - The direction of the scroll, one of the following: Muuri.AutoScroller.LEFT, Muuri.AutoScroller.RIGHT, Muuri.AutoScroller.UP, Muuri.AutoScroller.DOWN.
      - data.threshold  —  _number_
        - The current threshold in pixels.
      - data.distance  —  _number_
        - The handle rectangle's (as defined in handle option) current distance from the edge of the scroll element. E.g, if direction is Muuri.AutoScroller.RIGHT then distance is scrollElement.getBoundingClientRect().right - handleRect.right, and if direction is Muuri.AutoScroller.LEFT then distance is handleRect.left - scrollElement.getBoundingClientRect().left. Can be a negative value too.
      - data.value  —  _number_
        - The scroll element's current scroll value on the scrolled axis.
      - data.maxValue  —  _number_
        - The scroll element's maximum scroll value on the scrolled axis.
      - data.duration  —  _number_
        - How long (in milliseconds) this specific auto-scroll operation has lasted so far.
      - data.speed  —  _number_
        - The current speed as pixels per second.
      - data.deltaTime  —  _number_
        - requestAnimationFrame's delta time (in milliseconds).
      - data.isEnding  —  _boolean_
        - Is the scroll process ending? When this is true it means that the associated drag item does not satisfy the threshold anymore. You should now start decreasing the speed towards 0 to allow the item to come to rest smoothly.
  - Pro tip: Use Muuri.AutoScroller.smoothSpeed() for dynamic speed that provides a smooth scrolling experience. When executed it creates and returns a speed function which you can directly provide for speed option. The method _requires_ three arguments (in the following order):
    - maxSpeed  —  _number_
      - The maximum speed (pixels per second) when the handle's distance to the scroll target's edge is 0 or less.
    - acceleration  —  _number_
      - How fast the the speed may accelerate (pixels per second).
    - deceleration  —  _number_
      - How fast the the speed may decelerate (pixels per second).
- sortDuringScroll  —  _boolean_
  - Default value: true.
  - Should the grid items be sorted during auto-scroll or not?
- smoothStop  —  _boolean_
  - Default value: false.
  - When a dragged item is moved out of the threshold area the scroll process is set to _ending_ state. However, it's up to you to decide if the actual scrolling motion is stopped gradually or instantly. By default, when this is false, scrolling will stop immediately. If you set this to true scrolling will continue until speed drops to 0. When this option is enabled you _must_ handle decelerating the speed to 0 manually within speed function, so do not enable this option if you use a static speed value. The default speed function handles the deceleration automatically.
- onStart  —  _null / function_
  - Default value: null.
  - Optionally, you can provide a callback that will be called when an item starts auto-scrolling a scroll target. The callback function will receive the following arguments:
    - item  —  _Muuri.Item_
      - The dragged Muuri.Item instance.
    - scrollElement  —  _element_ / _window_
      - The scrolled element.
    - direction  —  _number_
      - The direction of the scroll, one of the following: Muuri.AutoScroller.LEFT, Muuri.AutoScroller.RIGHT, Muuri.AutoScroller.UP, Muuri.AutoScroller.DOWN.
- onStop  —  _null / function_
  - Default value: null.
  - Optionally, you can provide a callback that will be called when an item stops auto-scrolling a scroll target. The callback function will receive the following arguments:
    - item  —  _Muuri.Item_
      - The dragged Muuri.Item instance.
    - scrollElement  —  _element_ / _window_
      - The scrolled element.
    - direction  —  _number_
      - The direction of the scroll, one of the following: Muuri.AutoScroller.LEFT, Muuri.AutoScroller.RIGHT, Muuri.AutoScroller.UP, Muuri.AutoScroller.DOWN.
Examples
  1. ``` js
  2. // Create a fixed drag container for the dragged items, this is done with JS
  3. // just for example's purposes.
  4. var dragContainer = document.createElement('div');
  5. dragContainer.style.position = 'fixed';
  6. dragContainer.style.left = '0px';
  7. dragContainer.style.top = '0px';
  8. dragContainer.style.zIndex = 1000;
  9. document.body.appendChild(dragContainer);
  10. var grid = new Muuri(elem, {
  11.   dragEnabled: true,
  12.   dragContainer: dragContainer,
  13.   dragAutoScroll: {
  14.     targets: [
  15.       // Scroll window on both x-axis and y-axis.
  16.       { element: window, priority: 0 },
  17.       // Scroll scrollElement (can be any scrollable element) on y-axis only,
  18.       // and prefer it over window in conflict scenarios.
  19.       { element: scrollElement, priority: 1, axis: Muuri.AutoScroller.AXIS_Y },
  20.     ],
  21.     // Let's use the dragged item element as the handle.
  22.     handle: null,
  23.     // Start auto-scroll when the distance from scroll target's edge to dragged
  24.     // item is 40px or less.
  25.     threshold: 40,
  26.     // Make sure the inner 10% of the scroll target's area is always "safe zone"
  27.     // which does not trigger auto-scroll.
  28.     safeZone: 0.1,
  29.     // Let's define smooth dynamic speed.
  30.     // Max speed: 2000 pixels per second
  31.     // Acceleration: 2700 pixels per second
  32.     // Deceleration: 3200 pixels per second.
  33.     speed: Muuri.AutoScroller.smoothSpeed(2000, 2700, 3200),
  34.     // Let's not sort during scroll.
  35.     sortDuringScroll: false,
  36.     // Enable smooth stop.
  37.     smoothStop: true,
  38.     // Finally let's log some data when auto-scroll starts and stops.
  39.     onStart: function (item, scrollElement, direction) {
  40.       console.log('AUTOSCROLL STARTED', item, scrollElement, direction);
  41.     },
  42.     onStop: function (item, scrollElement, direction) {
  43.       console.log('AUTOSCROLL STOPPED', item, scrollElement, direction);
  44.     },
  45.   },
  46. });
  47. ```

option: containerClass

Grid element's class name.
- Default value: 'muuri'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   containerClass: 'foo',
  4. });
  5. ```

option: itemClass

Item element's class name.
- Default value: 'muuri-item'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   itemClass: 'foo-item',
  4. });
  5. ```

option: itemVisibleClass

Visible item's class name.
- Default value: 'muuri-item-shown'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   itemVisibleClass: 'foo-item-shown',
  4. });
  5. ```

option: itemHiddenClass

Hidden item's class name.
- Default value: 'muuri-item-hidden'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   itemHiddenClass: 'foo-item-hidden',
  4. });
  5. ```

option: itemPositioningClass

This class name will be added to the item element for the duration of positioning.
- Default value: 'muuri-item-positioning'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   itemPositioningClass: 'foo-item-positioning',
  4. });
  5. ```

option: itemDraggingClass

This class name will be added to the item element for the duration of drag.
- Default value: 'muuri-item-dragging'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   itemDraggingClass: 'foo-item-dragging',
  4. });
  5. ```

option: itemReleasingClass

This class name will be added to the item element for the duration of release.
- Default value: 'muuri-item-releasing'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   itemReleasingClass: 'foo-item-releasing',
  4. });
  5. ```

option: itemPlaceholderClass

This class name will be added to the drag placeholder element.
- Default value: 'muuri-item-placeholder'.
- Accepted types: string.
Examples
  1. ``` js
  2. var grid = new Muuri(elem, {
  3.   itemPlaceholderClass: 'foo-item-placeholder',
  4. });
  5. ```

Grid methods

- [getElement](#grid-method-ge