views:

97

answers:

2

I've got some code that's basically identical to the jQuery UI Sortable example here:

http://jqueryui.com/demos/sortable/#default

This allows users to re-order LI elements within a UL. I've now run into a situation, though, where I want to animate the LIs changing position... basically as if the user had dragged them herself. This is proving to be a lot more difficult than I'd expected, since I'm not animating a change that can be expressed in CSS, so jQuery's animate() isn't going to help.

I could solve the problem by doing some math and absolutely positioning the list elements, but that seems downright ugly. Is there an elegant way to animate my list elements moving around?

A: 

I'd create a helper div and animate that into position, then move the actual li and destroy the helper.

You can use$('#li').clone() to fill your helper, then absolutely position the helper div using the position from $('#li').offset(). Animate the helper to the new position ($('#target').offset()), destroy the helper (.remove()), and then reorder your <li>s.

josh3736
A: 

I'm not sure if this will help you, but I posted some script on animating an object after it was dragged in this paste bin.

Essentially, you animate the clone after the element is dropped:

 $("#droppable").droppable({
  drop: function(e, ui) {
   $(this).addClass('ui-state-highlight');
   var x = ui.helper.clone();
   x.appendTo('body')
    // move clone to original drag point
    .css({position: 'absolute',top: ui.draggable.position().top,left:ui.draggable.position().left})
    .animate({
     // animate clone to droppable target
     top: $(this).position().top, left: $(this).position().left},
     // animation time
     1500,
     // callback function - once animation is done
     function(){
      x.find('.caption').text("I'm being munched on!");
      ui.draggable.addClass('fade');
      // remove clone after 500ms
      setTimeout(function(){ x.remove(); }, 500)
     }
    );
   // remove the helper, so it doesn't animate backwards to the starting position (built into the draggable script)
   ui.helper.remove();
  }
 });
fudgey