I'm using jQuery UI Draggable to drag a <div>
whose width is calculated as part of the layout (margin:auto;
).
When dragging that element using helper:clone
, the clone also gets the margin:auto;
style, but is no longer constrained by the original's container.
Result: The cloned <div>
may have a different width than the original.
Fiddle: http://jsfiddle.net/ericjohannsen/ajpVS/1/
How can I cause the clone to retain the original's width?
Jon's answer is really good, but it doesn't work properly when you have child elements in the draggable. When that's the case, the event.target
can represent your draggable's children, and you'd want to modify the draggable's helper()
method something like:
$(".objectDrag").draggable({
helper: function(e) {
var original = $(e.target).hasClass("ui-draggable") ? $(e.target) : $(e.target).closest(".ui-draggable");
return original.clone().css({
width: original.width() // or outerWidth*
});
},
...
});
Without this, the helper would represent any child element clicked within the draggable (click the within the light blue region in the "Drag 1" box for example). Adding the additional logic above ensures that the draggable element is used for the helper. Hope that helps for anyone in a similar situation!
* Note: You'll want to use outerWidth
if the original element has box-sizing: border-box
applied (thanks to @jave.web for raising).
You just need to set the width and the margin on the cloned element based on the draggable object when it is dropped, using $(ui.draggable).clone().css({ ... });
Here's an updated fiddle for you, should be what you're looking for. It will also keep the width for the helper object as well. http://jsfiddle.net/ajpVS/2/
I think I know what the problem is.. where you have:
<div style="width:50px">
it also needs to be included in the objectDrag class:
<div class="objectDrag" style="width:50px;margin:auto; color:white;border:black 1px solid; background-color:#00A">Drag me</div>
I hope thats what you meant!
EDIT:
Hi took another quick look http://jsfiddle.net/He2KZ/1/
I used the width:inherit property to inherit the parents width no matter what size it is. Also I noticed removing the border fixed the problem. the dragable clone is 2px out and you have a border of 1px. This is kinda buggy from Jquery-ui IMO they should account for borders at least.
If you really want borders try using "outline" instead of "border". This does not add to the width of the div.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With