Fijjit
Fijjit

Reputation: 1467

Resizing a JQuery Draggable element's containment parent while dragging

I have a div 'slide' element within another div 'box' parent container and have applied JQuery Draggable to the child. While the item is being dragged, I'm resizing the parent container, sometimes shrinking, sometimes enlarging it.

The problem is that JQuery doesn't respond to this resizing and still contains the dragged element within the original dimensions of the parent, rather than within its current size, until mouseup - the next drag session will use the new dimensions (until it changes again).

To try and solve this, I was hoping to trigger the mouseup event followed by the mousedown event, so that JQuery will use the new container size:

$('.slide').draggable({ axis: "x", containment: 'parent',
                    drag: function (e, ui) {
                        resizeContainer();

                        if (outsideContainer()){

                        // Try to stop and restart dragging
                            $(this).trigger('mouseup');
                            $(this).trigger('mousedown');
                        }
                    }

However, this throws an exception...

Unable to get value of the property '0': object is null or undefined

...on this line of JQuery code:

this.helper[0].style.left=this.position.left+"px";

Anyone know how I can either a) get Draggable to respond real-time to the change in parent dimensions or b) trigger a dragstop and then dragend seamlessly?

Thanks.

Upvotes: 2

Views: 7066

Answers (1)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

@Fijjit, if I understand correctly, what you want is a custom "containment" function, which implements your resizeContainer algorithm before applying bounds to the dragged element.

In the code below,

  • the standard draggable containment option is omitted
  • resizeContainer is attached as the draggable drag event handler
  • resizeContainer is dual purpose; (a) it performs your resize algorithm and (b) applies the custom containment algorithm

javascript:

$(function(){
    var $container = $("#myContainer");

    function resizeContainer(e, ui) {
        //implement container resize algorithm here
        var w1 = ui.helper.outerWidth(),
            w2 = $container.width();
        ui.position.left = Math.max(Math.min(ui.position.left, w2 - w1), 0);
    }

    $("#draggable").draggable({
        axis: "x",
        drag: resizeContainer
    });
});

See fiddle demo

Upvotes: 3

Related Questions