Search code examples
jqueryjquery-uijquery-pluginsjquery-ui-draggablejquery-ui-droppable

jQuery, saving original position of multiple draggable objects to revert them back


Please see the jsfiddle

Once I drop the 'draggable' object on the target, that particular position is used next time, when reverting back. Is there any way by which I can save the original positions of the draggable objects and always revert them back to them (the very first positions)? Or is there any other solution than 'saving them' to achieve the same goal?

I found somewhat similar question, but the positions(left, top) are hardcoded in them to revert back. I tried hard but couldn't find a solution.

Thank you.


Solution

  • I'm assuming that when you drop your draggable on the target, you don't want it to revert, but after you move it back out of the target, you'd like it to revert back to its original position with the rest of the draggables?

    If that's the case, the code in this answer is what you're looking for, and although the values 0, 0 for the top and left locations seem hard-coded, they are necessary as the draggables' position CSS attributes get set to relative after they've been turned into draggables, so setting them back to 0, 0 would move them back to their original positions.

    Here's a jsfiddle example, and also the modified code in your example:

    $('#target').droppable({
    
        // you need to set revert to a function as the 'out' event is turning it
        // into a function...
        drop: function(event, ui){
            ui.draggable.draggable('option', 'revert', function(){return false});
        },
    
        out: function(event, ui){
            ui.draggable.draggable('option', 'revert', function(){
                $(this).data('draggable').originalPosition = {
                    top: 0,
                    left: 0
                };
                return true;
            });
        }
    });
    

    Hope this helps! Please let me know if I've missed the mark completely!