Moving an item programmatically with jQuery sortable while still triggering events

RailsSon picture RailsSon · Feb 6, 2011 · Viewed 25.3k times · Source

I am using jQuery Sortable. I have the HTML setup like so:

<ul id='plan'>
  <li class='item'>1</li>
  <li class='item'>2</li>
  <li class='item'>3</li>
  <li class='item'>4</li>
</ul>

I want to programmatically move an <li> to a different position. I can achieve this with the following JS:

$("#plan li:eq(1)").insertAfter($("#plan li:eq(2)"));

This works fine except it does not trigger the sortable events like change or update. I have a function which is run on the update event of the sortable but moving the li with JS does not trigger this.

Does anyone know how to trigger the sortable update event?

Answer

Luke picture Luke · Feb 6, 2011
$("selector").trigger("sortupdate");

you will have to maybe pass in as second argument a function where to put in the event and the ui, event is not as important as ui

the inside code of the sortable widget for event triggering looks like this

this._trigger("update", event, this._uiHash(this));

So you may want to do following

function triggerUpdateFor(selector) {
    var widget = $(selector).sortable("widget");
    if (widget) widget._trigger("update", null, widget._uiHash(widget));
}