Neel
Neel

Reputation: 625

drag child elements when parent is dragged - jquery ui draggable

I have created a visualization of planned activities in gantt chart form based on jsgantt library. Each activity should be draggable and I have accomplished that through jQuery UI draggable library.

HTML

<div class="container">
<div id="task_1" class="parent_bar" style="height:30px;width:190px"></div>
<div id="task_2" class="child_bar1"></div>
<div id="task_3" class="child_bar2"></div>
<div id="task_4" class="child_bar3"></div>

<div id="task_5" class="parent_bar" style="height:30px;width:150px"></div>
<div id="task_6" class="child_bar1"></div>
<div id="task_7" class="child_bar2"></div>
<div id="task_8" class="child_bar3"></div>

</div>

jQuery Code

$(document).ready(function(){

    $(".child_bar1,.child_bar2,.child_bar3").draggable({
        axis:"x",
        containment: ".parent_bar"
    });

});

http://jsfiddle.net/mm0efp9a/

Requirement: When a parent bar is dragged the child items should be dragged along with it. Problem: There is no container element for parent and child items. They are rendered as siblings.

Is it possible to automatically drag multiple elements when one particular element is being dragged.

P.S. This is not exact code I am using but very similar to actual code. I have an array which contains information about parent-child relation that I am using to dynamically define child containment div based parent location.

Upvotes: 2

Views: 6077

Answers (1)

simpleManderson
simpleManderson

Reputation: 436

If you can modify the HTML, you can wrap each list and make the wrapper draggable, with the handle option set to the 'parent' element. This will allow you to drag the entire list around only via the 'parent' and still be able to make each 'child' element draggable as well. See https://jqueryui.com/draggable/#handle for details.

Updated fiddle with relevant snippets below. Also, had to trigger shrink-to-fit on the wrapper element, otherwise it fills its entire parent width and can't be dragged if containment is set. Easiest way I could think of was .task_list{display:table;}

HTML:

<div id="task_list_1" class="task_list">
    <div id="task_1" class="parent_bar" style="height:30px;width:190px">    </div>
    <div id="task_2" class="child_bar1"></div>
    <div id="task_3" class="child_bar2"></div>
    <div id="task_4" class="child_bar3"></div>
</div>

JS:

$(".task_list").draggable({
        handle: $(".parent_bar"),
        containment: ".container"
    });

Upvotes: 1

Related Questions