Given the following list
<ul class="listitems">
<li data-position="1">Item 1</li>
<li data-position="2">Item 2</li>
<li data-position="3">Item 3</li>
<li data-position="4">Item 4</li>
</ul>
there is some functionality on the page that will allow the possibility of these items changing position. For example, they may get to the following state (example only, the order could be anything):
<ul class="listitems">
<li data-position="3">Item 3</li>
<li data-position="2">Item 2</li>
<li data-position="1">Item 1</li>
<li data-position="4">Item 4</li>
</ul>
I am looking for a small function to reset the order. So far I have the following:
function setPositions()
{
$( '.listitems li' ).each(function() {
var position = $(this).data('position');
$(this).siblings().eq(position+1).after(this);
});
}
But it isnt working correctly. What am i doing wrong?
An additonal condition is that the order of the list might not have changed, and so the function has to work in that scenario also.