Search code examples
jqueryjquery-uiclonedraggable

Jquery ui weird behaviour with .clone(true,true) + .remove()


I am experiencing a wierd behaviour with jquery-ui and jquery .clone() , remove(). I am using jquery 1.7 and jquery-ui 1.8.16. The problem is when i remove an element from a deep cloned element using remove() function , the remove affects the cloned element AND the corresponding element in the document by removing the draggable properties from the element in the DOM. I'm not sure if i'm doing anything wrong but it seems to me like either my misunderstanding of how clone(true,true) works or a bug in jquery-ui.

consider the following

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js" type="text/javascript"></script>
  <script type="text/javascript">
  $(document).ready(function() {
    $('#testp').draggable();
    //the following line causes the draggable classes to be removed from the document
    //as well as the cloned object ,the expected behaviour is that that #testp will be 
    //removed only from the clone...
          var test = $("#test")
           .clone(true,true)
           .find('#testp')
           .remove()
           .end(); //some more manipulation here
        });
  </script>
</head>
<body>
  <div id="test">
    <p id="testp">some text</p>
  </div>
</body>
    </html>

UPDATE: It seems that .clone(true,true) still keeps some data shared among the clone and the original. Even with changing the ids/applying .draggable() with a class selector and not removing any element from the dom, dragging the clone will move the original and not effect the clone(as one would think). other handlers like click etc ,are cloned correctly

After seeing some posts about issues cloned divs with (true,true) and draggable plugin, i've decided to refrain from cloned divs copying etc and just use detach() and reattach as a workaround.

Note to others who tried clone(true,true) to clone divs with draggable() plugin applied: if you clone(true,true) some data will be copied to the clone and by applying draggable() to it you'll be dragging the original, and i guess that's not what you intened to do. instead do a shallow .clone() and then bind draggable() to the clone.


Solution

  • Try separate statements:

    var test = $("#test");
    test.clone(true,true).appendTo("whatever").find('#testp').remove();
    

    PS: clone() and remove() are in jQuery core. Presence of jQuery UI should not affect them but by all means try without UI installed.