How do I drag multiple elements at once with JavaScript or jQuery?

I am the author of the of the threedubmedia plugins. I added this functionality for supporting multiple elements, because I could not find a satisfactory solution anywhere else.

If you need a solution that works with the jQuery UI, here is a plugin which adds some multi-drag functionality, though the demos don't seem to work correctly in Firefox for Mac.

http://www.myphpetc.com/2009/11/jquery-ui-multiple-draggable-plugin.html


var selectedObjs;
var draggableOptions = {
    start: function(event, ui) {
        //get all selected...
        selectedObjs = $('div.selected').filter('[id!='+$(this).attr('id')+']');
    },
    drag: function(event, ui) {
        var currentLoc = $(this).position();
        var orig = ui.originalPosition;

        var offsetLeft = currentLoc.left-orig.left;
        var offsetTop = currentLoc.top-orig.top;

        moveSelected(offsetLeft, offsetTop);
    }       
};

$(document).ready(function() {
    $('#dragOne, #dragTwo').draggable(draggableOptions);
});

function moveSelected(ol, ot){
    console.log(selectedObjs.length);
    selectedObjs.each(function(){
        $this =$(this);
        var pos = $this.position();

        var l = $this.context.clientLeft;
        var t = $this.context.clientTop;

        $this.css('left', l+ol);
        $this.css('top', t+ot);
    })
}

This worked for me.

Fiddle here:

var selectedObjs;
var draggableOptions = {
start: function(event, ui) {
    //get all selected...
    if (ui.helper.hasClass('selected')) selectedObjs = $('div.selected');
    else {
        selectedObjs = $(ui.helper);
        $('div.selected').removeClass('selected')
    }
},
drag: function(event, ui) {
    var currentLoc = $(this).position();
    var prevLoc = $(this).data('prevLoc');
    if (!prevLoc) {
        prevLoc = ui.originalPosition;
    }

    var offsetLeft = currentLoc.left-prevLoc.left;
    var offsetTop = currentLoc.top-prevLoc.top;

    moveSelected(offsetLeft, offsetTop);
    selectedObjs.each(function () {
           $(this).removeData('prevLoc');
        });
    $(this).data('prevLoc', currentLoc);
}
};

$('.drag').draggable(draggableOptions).click(function()     {$(this).toggleClass('selected')});


function moveSelected(ol, ot){
console.log("moving to: " + ol + ":" + ot);
selectedObjs.each(function(){
    $this =$(this);
    var p = $this.position();
    var l = p.left;
    var t = p.top;
    console.log({id: $this.attr('id'), l: l, t: t});


    $this.css('left', l+ol);
    $this.css('top', t+ot);
})
}

Thanks to ChrisThompson and green for the almost-perfect solution.