jake
jake

Reputation: 1939

jQuery UI Draggable: Update containment on drag event

Is this possible: Create a draggable element so that when it is dragged over a specific droppable element, the draggable element's containment option is set to the droppable element? This would create an effect where dragging something over a droppable element causes the draggable element to get locked/stuck to the confines of the droppable element.

Below is an excerpt from my code, although it fails to accomplish the above effect.

var droppable_position = $('#droppable').position();
$('#draggable').draggable({
    helper: 'clone',
    drag: function (event, ui) {
        if (ui.position.left > droppable_position.left && ui.position.top > droppable_position.top)
        {
            $('#draggable').draggable('option', 'containment', '#droppable');
        }
    }
});

Upvotes: 1

Views: 7544

Answers (1)

sdespont
sdespont

Reputation: 14025

You could overwrite the position of the element being dragged.

Here is not the code "ready to go" but pieces permitting to develop yourself. The idea is to set containment positions variables in the hover event of your droppable element and test them with the current dragging position in the drag event of your dragging element.

This fiddle is an example of the position overriding : http://jsfiddle.net/QvRjL/74/

This fiddle is an example of how you could do to check if the dragged element is near a border of your container : http://jsfiddle.net/pPn3v/22/

Position overwriting example :

$(document).mousemove(function(e){
   window.mouseXPos = e.pageX;
   window.mouseYPos = e.pageY;
}); 

$('[id^="drag-"]').each(function() {
    $(this).draggable({
        opacity: 0.7,
        cursorAt: { top: 15, left: 50 },        
        scroll: true,
        stop: function(){},  
        drag : function(e,ui){            
            //Force the helper position
            ui.position.left = window.mouseXPos - $(this).draggable('option','cursorAt').left;
            ui.position.top = window.mouseYPos- $(this).draggable('option','cursorAt').top; 
        });
});

Upvotes: 2

Related Questions