Search code examples
javascriptjqueryjquery-uijquery-draggablejquery-droppable

jquery draggable containment array values for scaled container


If anyone could help me figure out how to make the draggable elements contained in a div that changes scale based on window size, i'd really appreciate any guidance.

If I do:

element.draggable({ 
    cursor: "move",
    containment: '#container'
});

What will happen is it gives me the containment for the regular size of the container. So if I have a transform: scale(1.5), there will be space in the container that the draggable element can not go.

I've also tried containment: 'parent' but that get's very glitchy.

EDIT

I've found out how to get the top and left containment but I can't figure out how to get the right and bottom.

var containmentArea = $("#container");

containment:  [containmentArea.offset().left, containmentArea.offset().top, ???, ???]

I've tried width and height from containmentArea[0].getBoundingClientRect() but that doesn't seem to be the right move either.


Here is a jsfiddle of some example code.


Solution

  • A version with resetting the coordinates in the drag event (since they were being recalculated already for the scale transformations), without using the containment:

    var percent = 1, containmentArea = $("#container");
    
    function dragFix(event, ui) {
        var contWidth = containmentArea.width(), contHeight = containmentArea.height();
        ui.position.left = Math.max(0, Math.min(ui.position.left / percent , contWidth - ui.helper.width()));
        ui.position.top = Math.max(0, Math.min(ui.position.top  / percent,  contHeight- ui.helper.height()));
    }
    
    $(".draggable").draggable({
        cursor: "move",
        drag: dragFix,
    });
    
    //scaling here (where the percent variable is set too)
    

    Fiddle

    In the example width and height of the container are obtained inside the dragevent, you could also store them when scaling for better performance. By having them calculated inside the event, they still work after rescaling, although the percent variable still has to be set. To be truly generic, it could be obtained inside the event as well (and instead of a fixed container, ui.helper.parent() could be used) Since the offset inside the dragevent is (0,0) related to the container (at least it is for the current setup), took the liberty of simplifying originalleft + (position - originalposition)/percent to position / percent Start offset didn't seem to be necessary any more, so left it out in the fiddle, but can be re-added if needed.