--- layout: default title: Shuffle Adding and Removing Elements Demo description: This demo of shuffle shows how to add and removing items. image: /demos/adding-removing.jpg extraJS: [ "demos/adding-removing.js" ] prism: true ---

Adding and Removing Items

When you add elements to the Shuffle container, notify the Shuffle instance with the add method. You must add the elements to the DOM yourself. This lets you control the default (DOM) sort order.

When you want to remove item(s), use remove. This will fade out the item(s) then remove it from the DOM.

Sort:

Adding elements

Wherever you add the element in the DOM is where it will show up in the grid (assuming you’re using the default sort-by-dom-order). With this in mind, you can append, prepend, or insert elements wherever you need to get them to show up in the right order.

Demo.prototype.setupEvents = function () {
  document.querySelector('#append').addEventListener('click', this.onAppendBoxes.bind(this));
};

/**
 * Create some DOM elements, append them to the shuffle container, then notify
 * shuffle about the new items. You could also insert the HTML as a string.
 */
Demo.prototype.onAppendBoxes = function () {
  var items = this._getArrayOfElementsToAdd();

  items.forEach(function (item) {
    this.element.appendChild(item);
  }, this);

  // Tell shuffle items have been appended.
  // It expects an array of elements as the parameter.
  this.shuffle.add(items);
};

Removing elements

Shuffle will animate the element away and then remove it from the DOM once it's finished. It will then emit the Shuffle.EventType.REMOVED custom event with the array of elements in event.detail.collection.

this.shuffle.remove([element1, element2]);

Source code for this demo

Demo source