Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Ensure Dragged Element Clone Retains Original's Width

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?

like image 437
Eric J. Avatar asked Feb 15 '13 00:02

Eric J.


3 Answers

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).

like image 141
Ian Clark Avatar answered Nov 12 '22 05:11

Ian Clark


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/

like image 29
Jon Bos Avatar answered Nov 12 '22 07:11

Jon Bos


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.

like image 20
Hiren Umradia Avatar answered Nov 12 '22 06:11

Hiren Umradia