Reputation: 11
I am using jQuery draggable plugin and faced with the next problem. After draggable creation, plugin doesn't apply specified containment option.
Here you can find an example: http://jsfiddle.net/qQYsj/.
// Containment will be applied after first move attempt
$('.item').draggable({ containment: [100, 100, 200, 200] });
Is there a way to apply containment without extra logic, that will calculate allowed position and place element to it? (this logic already exist in the plugin)
Thx.
Upvotes: 1
Views: 144
Reputation: 11
I didn't find any possible solution without adding duplicate logic (positioning algorithm already exist in draggable plugin, but i can't force plugin to execute it).
So i added next code to update item position:
function updateItemPosition(item, container)
{
var itemRect = getRect(item), currentPosition = item.position(),
position = getItemPosition(getRect(container), itemRect);
item.css('top', position.top - itemRect.top + currentPosition.top + 'px')
.css('left', position.left - itemRect.left + currentPosition.left + 'px');
}
function getRect(target)
{
var result = target.offset();
result.width = target.outerWidth();
result.height = target.outerHeight();
return result;
}
function getItemPosition(containerRect, itemRect)
{
var result = {};
result.top = Math.max(containerRect.top, Math.min(containerRect.top + containerRect.height - itemRect.height, itemRect.top));
result.left = Math.max(containerRect.left, Math.min(containerRect.left + containerRect.width - itemRect.width, itemRect.left));
return result;
}
And it should be used like:
updateItemPosition($('.item'), $('.placeholder'));
Upvotes: 0
Reputation: 16180
I think that your draggable containment is working as its intended to. Your draggable element isn't within that container though.
Why not just use CSS to place your .item
inside the containment area to begin with?
.item
{
position:absolute;
top: 100px;
left:100px;
width: 100px;
height: 100px;
border: 1px solid red;
}
On second thought, when you say "simulate dragging" are you talking about something like this:
// drag will start after dragging 100px
$('.item').draggable({
containment: [100, 100, 200, 200],
distance: 100
});
Upvotes: 0
Reputation: 22557
Not sure if this is what you were looking for, but this might be an option...
.item
{
width: 100px;
height: 100px;
border: 1px solid red;
position: absolute;
}
// Containment will be applied after first move attempt
var xpos = 100,
ypos = 100;
$('.item').css({
"top": ypos+"px",
"left": xpos+"px"
}).draggable({ containment: [ypos, xpos, 200, 200] });
Upvotes: 1