I have a little project I\'m working on, and have an interesting containment issue using jquery\'s draggable
:
Basically, I have two divs - a top & a
Admittedly the documentation is thin - I had to do a lot of testing to figure it out.
My mistake was in thinking that the containment array defined a boundary within which the draggable element could move, defined as [x, y, width, height], but I've found that the containment array defines the upper left and lower right points that define the boundary defined as [x1, y1, x2, y2] that the contained elements origin can move within.
This makes sense in that the last two array elements are defined as x2 and y2 (point properties), not w and h (rectangle properties), but the documentation should be more specific as to exactly what these parameters mean in context to the contained element, and within what context (against the contained element's origin) and coordinate system (the contained element's).
The containment option allows an array where to set the positions where to contain it. Try this:
var containmentTop = $("#stop-top").position().top;
var containmentBottom = $("#stop-bottom").position().top;
$('#bar').draggable({axis: 'y', containment : [0,containmentTop,0,containmentBottom] });
JSFiddle example
You can constrain the containment in a bounding-box delimited by the 2 stop elements :
var top = $("#stop-top").offset().top + $("#stop-top").height();
var bottom = $("#stop-bottom").offset().top - $("#bar").height();
$('#bar').draggable({axis: 'y', containment : [0, top, 10000, bottom] });
JsFiddle : http://jsfiddle.net/Kpt2K/9/
You can also use a helper:
and this will allow you to add a div
which you can dynamically set the size of prior the draggable action occurring. This allows you reference it in containment although it's not actually part of the page yet. If you use start:
, this div
won't be there by the time draggable function looks for containment element. You can clean up in the stop:
$(<<selector>>).draggable({
helper: function (event, ui) {
var target = $(this).clone();
var oBody = $(document).find('body');
var containmentDiv = $('<div id="div_containment"></div>');
containmentDiv
.css('top',calculatedTop)
.css('left',calculatedLeft)
.css('width',calculatedWidth)
.css('height',calculatedHeight)
.css('position','absolute');
containmentDiv.appendTo(oBody);
target.children('div').remove();
target.css('background-color','#f00');
return target;
},
stop: function(event, ui) {
$(document).filter('body').find('#div_containment').remove();
},
containment: "#div_containment" //containment via selector
});
You can use a JavaScript object reference to set calculated values in helper:
elsewhere