T J T J - 6 months ago 30
jQuery Question

Dragging the container sortable itself when all items are selected

I want to drag the whole sortable (according to a condition) while dragging an item inside it.

Following is the HTML structure

<div id='container'>
<div class='parent'>
<div class='child'>1</div>
<div class='child'>2</div>
</div>
<div class='parent'>
<div class='child'>3</div>
<div class='child'>4</div>
</div>
</div>


And the simple script:

$('#container').sortable();

$('.parent').sortable({
connectWith: '.child',
tolerence: 'pointer'
});

$('.child').click(function () {
$(this).toggleClass('selected').parent().toggleClass('selectedGroup');
});


I want to drag the child if it's alone selected, if all children in a parent sortable is selected, while dragging any of it's child I want to drag the whole parent instead of the particular child being dragged.

For another example, assume when the child which is being dragged is the only child of it's parent then I want the parent to be dragged instead of the child alone being dragged out of it's parent.

I've tried to accomplish this using
z-index
, by applying a higher
z-index
for parent when I want to drag it, but as long as they're in same stacking context, it doesn't seem to work, still the child alone is being dragged.

Here's a JSFiddle which better demonstrates what I've tried and what I want to do..

(you'll be able to drag the parent if you click in the space between child elements)

Any ideas for doing so would be great...

T J T J
Answer

Update

I managed to sort the parent sortable as a whole by disabling it if all items inside it are selected as follows

$('.child').click(function () {
 $(this).toggleClass('selected');
 if (!$(this).parent().find(':not(.selected)').length)
  $(this).parent().sortable('disable');
 else
  $(this).parent().sortable('enable');
});

Demo


Okay, looks like i've figured it out a temporary solution which does not work cross browser :

By disabling click event on childs with a selected group by setting it's css pointer-events property to none.

CSS

.selectedGroup .child {
 pointer-events:none; /* disable clicks on child elements of a selected group */
}

Script

$('#container').sortable();

$('.parent').sortable({
 connectWith: '.parent',
 tolerence: 'pointer'
});

$('.child').click(function () {
 $(this).toggleClass('selected');
 if (!$(this).parent().has(':not(.selected )').length) { //check whether there are any unselected items in the group
    $(this).parent().addClass('selectedGroup');
 }
});

JSFiddle