JQuery Draggable object resize while dragging

I have a div element 'slide' in the parent container of the div 'box' and applied JQuery Draggable to the child. While the item is being dragged, I resize the parent container, sometimes shrinking, sometimes increasing it.

The problem is that jQuery does not respond to this resizing and still contains the draggable element in the original dimensions of the parent, and not within its current size, to the mouse - the next drag and drop session will use the new dimensions (until it changes again).

To try to solve this problem, I was hoping to trigger a mouseup event, followed by a mousedown event, so that jQuery would 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 

... in this line of jQuery code:

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

Does anyone know how I can: a) get Draggable to respond in real time to changes in the parent dimensions or b) trigger a drag and then drag smoothly?

Thank.

+2
jquery triggers draggable
May 04 '12 at 21:15
source share
1 answer

@Fijjit, if I understand correctly what you want, this is a custom containment function that implements your resizeContainer algorithm before applying constraints to the dragged item.

In the code below

  • standard option draggable containment omitted
  • resizeContainer attaches as a draggable drag event handler
  • resizeContainer - dual purpose; (a) it implements a resizing algorithm; and (b) applies a user 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 }); }); 

Watch a demo of the script

+3
May 05, '12 at 1:28
source share



All Articles