user2616550
user2616550

Reputation: 113

jQuery UI draggable collections: dragging elements simultaneously

I'm currently trying to build a draggable collection of items in jQuery UI for a Timeline type functionality. I've tried a number of things using the current example I have in the following jsFiddle (http://jsfiddle.net/cyVYq/) however none of my attempts have given me the result i'm after.

<div style="width: 99%; overflow: auto;position:absolute;">

        <div class="TimelineContainer">
            <div class="Task">
                <div id="coords"></div>
            </div>
            <div class="Event">
            </div>
            <div class="Resource">
            </div>
        </div>

</div>

Ideally, I'd like to maintain the spacings between all the child divs when I drag the collection so that they all move simultaneously as one group on drag. Currently I can only achieve them moving independently but in reality these items are linked together.

There may also be a requirement however to pull the child objects up to the start of the parent div. Are either of these options possible?

Any help appreciated!

Cheers

Upvotes: 2

Views: 1693

Answers (1)

Daniel Gimenez
Daniel Gimenez

Reputation: 20609

You want all three items to move as a group when dragged, but the individual X values can be changed elsewhere in your code.

The following updates old three items when any of them are dragged. Each item has its starting point saved when dragging begins. As the drag event is called, the change of the one item is applied to the other two items.

var $elements = [$('.Task'), $('.Event'), $('.Resource')];

$(".Task, .Event, .Resource").draggable({
    axis: "x",
    containment: "parent",
    start: function (ev, ui) {
        var $elem
        for (var i in $elements) {
            $elem = $elements[i];
            if ($elem[0] != this) {
                $elem.data('dragStart', $elem.offset());
            }
        }
    },
    drag: function (ev, ui) {
        var xPos, $elem,
        deltaX = ui.position.left - ui.originalPosition.left;
        for (var i in $elements) {
            $elem = $elements[i];
            if ($elem[0] != this) {
                $elem.offset({
                    top: $elem.data('dragStart').top,
                    left: Math.max($elem.data('dragStart').left + deltaX, 8)
                });

            }
        }
    }
})

jsFiddle

You can easily make the items independent and then relink them by populating and clearing the $elements array.

function unlink() {
   $elements = []; 
};

function link() {
   $elements = [$('.Task'), $('.Event'), $('.Resource')];
};

Upvotes: 3

Related Questions