RailsSon RailsSon - 5 months ago 93
jQuery Question

Moving an item programmatically with jQuery sortable while still triggering events

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
$("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));
}