Sortable: API Calls to manipulate the objects programatically

Created on 22 Jan 2015  路  15Comments  路  Source: SortableJS/Sortable

I would like to implement "up" "down" buttons, and manipulate the sortable order programatically. The way I found through the docs seems to be outputting the order to an array, manipulating it, and then sorting based on that array. Is this the only/best way?

question

Most helpful comment

@etcook http://jsbin.com/mowoxofela/1/edit?js,output

// Manipulation without DOM
var array = sortable.toArray();
var first = array.splice(0, 1)[0]; // get first
array.push(first); // move to end
sortable.sort(array);

// DOM manipulation
/**
 * Move an item
 * @param {number} index
 * @param {number} toIndex
 */
Sortable.prototype.moveItem = function (index, toIndex) {
  var itemEl = this.el.children[index],
      toEl = this.el.children[toIndex];

  this.el.insertBefore(itemEl, toEl && (+toIndex ? toEl.nextElementSibling : toEl));
};

var sortable = Sortable.create(simpleList);
// ...
sortable.moveItem(0, 3);

All 15 comments

:+1:

@RubaXa So, insert a copy of the item with insertBefore and then remove the old item? Is that what you're suggesting? Thanks again!

@RubaXa I wish I was even 1/4 as fast as you. Thanks!

@etcook Enjoy ;]

That is a cool example, but how exactly does onFilter work? The documentation needs improvement. It seems to work like a click handler here, but the documentation suggests something quite different.

In my use case, I require the ability to control the items with elements outside of the dom of the repeatable item, therefore the onFilter trick won't work.

I replicated the dom behavior successfully, however the underlying model is not updated with the new sort value. Any suggestions?

@RubaXa Any suggestions on this? I appreciate any guidance. I need to do it from an element outside the scope/dom of the sortable object.

@etcook http://jsbin.com/mowoxofela/1/edit?js,output

// Manipulation without DOM
var array = sortable.toArray();
var first = array.splice(0, 1)[0]; // get first
array.push(first); // move to end
sortable.sort(array);

// DOM manipulation
/**
 * Move an item
 * @param {number} index
 * @param {number} toIndex
 */
Sortable.prototype.moveItem = function (index, toIndex) {
  var itemEl = this.el.children[index],
      toEl = this.el.children[toIndex];

  this.el.insertBefore(itemEl, toEl && (+toIndex ? toEl.nextElementSibling : toEl));
};

var sortable = Sortable.create(simpleList);
// ...
sortable.moveItem(0, 3);

@RubaXa

clap clap

Shouldn't this also trigger the onSort event?

How can do this with animation?

@sean-mcclure Maybe take a look at this library: https://github.com/owen-m1/Animatum
I made it from the code of Sortable, so you can have the same animation system Sortable has but edit the DOM is whatever way you like.

sortable.moveItem(0, 3);

This doesn't seem to be work in 2021, any ideas ?

Was this page helpful?
0 / 5 - 0 ratings