Search code examples
jqueryclonedraggable

Jquery draggable element when cloned not draggable


After looking at all the jquery draggable clone possible duplicates, I still can't find the answer to what must be a fairly common issue.

I have a series of DIV elements that I can clone successfully, but each clone loses it's draggable capability, I've looked at the generated code and still can't work out why this is.

Any clues please?

<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Sortable - Cloning issue</title>
<style>
.bgblue {
background-color:#9CF;
}
.bgred {
      background-color:#F36;
  }

  </style>

  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="JS/ui/jquery-ui-1.10.3.custom.min.js"></script>


  <script>

  function seCopyBox(x) {
    z = $('.seBox').eq(x).clone();
    z.insertAfter($('.seBox').eq(x));
} 

$(function() {
$( ".seBox" ).draggable();
  });

  </script>

</head>
<body>



<div class="seBox bgblue">
<p onClick="javascript:var x=$(this).closest('.seBox').index();seCopyBox(x)">COPY</p>
<p>Div A</p>
</div>

<div class="seBox bgred">
<p onClick="javascript:var x=$(this).closest('.seBox').index();seCopyBox(x)">COPY</p>
<p>Div B</p>
</div>

<div class="seBox bgblue">
<p onClick="javascript:var x=$(this).closest('.seBox').index();seCopyBox(x)">COPY</p>
<p>Div C</p>
</div>


</body>


Solution

  • call draggable() again for the cloned element after it is appended to the DOM

     function seCopyBox(x) {
       z = $('.seBox').eq(x).clone();
       z.insertAfter($('.seBox').eq(x)).draggable();
    } 
    

    and i would go with clean jquery click function rather that inline javascript..

    $(document).on('click','.seBox p',function(){
       var x=$(this).closest('.seBox').index();
        var z = $('.seBox').eq(x).clone();
        z.insertAfter($('.seBox').eq(x)).draggable();
    }
    

    remove the inline javascript and the seCopyBox function...