Draggable SO question

by Luis Lebolo

HTML

<div class="parent">
    <div class="child"></div>
</div>
<div class="drag"></div>

CSS

.parent {
    border: 1px solid black;
    overflow: visible;
    width: 100px;
    height: 100px;
    position: absolute;
    left: 100px;
}
.child {
    width: 200px;
    height: 100px;
    background-color: red;
    float: right;
    opacity: .5;
}
.drag {
    width: 50px;
    height: 50px;
    background-color: blue;
    position: absolute;
    left: 250px;
}

JavaScript

$(".drag").draggable();
$(".child").droppable({
    drop: function (event, ui) {
        /*
         * Check if draggable is inside the parent. This is a bit brute force, if
         * the parent itself is also a droppable it can also be checked by
         * listening for the 'over' event and setting a flag.
         */
        var pPos = $(".parent").offset(); // the parent container's position
        var dPos = ui.offset; // the current draggable's position

        // Can also add right/top/bottom contraints if required...?
        var withinParent = dPos.left > pPos.left;

        if (!withinParent) {
            // Move the draggable to its original position (or some safe spot)
            ui.draggable.animate(ui.draggable.data().draggable.originalPosition, "slow");
        }
    }
});