Question

Using jQueryUI's draggable plug-in, I want to make any drag events in the parent container move a specific, single child regardless if the click and drag event started on the child or not.

Consider this simple example: http://jsfiddle.net/9rqHe/

HTML:

<div id="parent">
    <div id="child">Child</div>
</div>

CSS:

#parent {
    width: 100%;
    height: 400px;
    border: 1px solid red;
    overflow: hidden;
}

#child {
    width: 50%;
    height: 50%;
    background-color: green;
    cursor: move;
}

JS:

$(document).ready(function() {
    $('#child').draggable();
});

Is it possible to delegate the draggable action on the parent to make the child move?

The handle option seems like it would work if it wasn't for this important caveat:

If specified, restricts dragging from starting unless the mousedown occurs on the specified element(s). Only elements that descend from the draggable element are permitted.

Nothing else in the API documentation seems to point to this being possible out-of-the-box unless I'm completely missing something.

Was it helpful?

Solution

There's no built-in way to do this. but you can get a similar effect with an extra div and some jQuery and CSS.

jsFiddle example

HTML

<div id="parent">
    <div id="child">Child</div>
    <div id="ghost"></div>
</div>

jQuery

var childX = 0,
    childY = 0;
$('#ghost').draggable({
    drag: function (event, ui) {
        $('#child').offset({
            top: childY + ui.offset.top,
            left: childX + ui.offset.left
        });
    },
    stop: function (event, ui) {
        $(this).offset({
            top: 0,
            left: 0
        });
        childX = $('#child').offset().left;
        childY = $('#child').offset().top;
    }
})

CSS

#parent {
    width: 100%;
    height: 400px;
    border: 1px solid red;
    overflow: hidden;
    position:relative;
}
#child {
    width: 50%;
    height: 50%;
    background-color: green;
    cursor: move;
    position:relative;
    z-index:1;
    pointer-events:none;
}
#ghost {
    height:100%;
    width:100%;
    position:absolute;
    top:0;
}

OTHER TIPS

A dirty hack I came up with on the fly since triggering the drag event doesn't work anymore for some reason.

JSFiddle

Basically I put a child element into the #child div and use a jQuery event function to always position it over the #parent div.

function updatehack(e,ui)
{
    $('#hack').width($('#parent').width());
    $('#hack').height($('#parent').height());
    var p=$('#child').position();
    $('#hack').css('top',-p.top);
    $('#hack').css('left',-p.left);
}


$('#child').draggable({
    stop:updatehack   
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top