BoundForGlory
BoundForGlory

Reputation: 4417

jQuery drag and drop with dynamic elements

I dynamically create dom elements with jQuery, then I make them draggable. I have my drop target, but the elements will not drag. What could be the problem? Here is the entire page:

  <!doctype html>
     <html lang="en">
       <head>
        <meta charset="utf-8">
         <title>jQuery UI Droppable - Default functionality</title>
            <link rel="stylesheet"href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <style>
    #draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
     #droppable { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
   ul
  {
      list-style-type: none;
  }
   </style>
    <script>
   $(function() {
  $( "#draggable" ).draggable();
  $( "#droppable" ).droppable({
    drop: function( event, ui ) {
     $( this )
        .addClass( "ui-state-highlight" )
       .find( "p" )
        .html( "Dropped!" );
     }
  });
    for (var i = 0; i < 9;i++){
     var li = $('<li>');
      var btn = $("<button type='button' tabindex='-1' class='matrix-item' data-value='" + i + "' title='" + "My title" + "'> Button " + i + "</button>").draggable();
              li.append(btn);
             $(".holder ul").append(li);}
  });
 </script>
 </head>
  <body>

 <div id="draggable" class="ui-widget-content">
  <p>Drag me to my target</p>
</div>

<div id="droppable" class="ui-widget-header">
 <p>Drop here</p>
</div>

<div id="container">
  <div class="holder">
    <ul></ul>
    </div>
</div>
 </body>
 </html>

Thanks in advance.

Upvotes: 0

Views: 1859

Answers (1)

indubitablee
indubitablee

Reputation: 8206

you cant drag buttons cause buttons have default click functions. if you switch them to divs, it'll work. check it out here: http://jsfiddle.net/swm53ran/319/

var btn = $("<div type='button' tabindex='-1' class='matrix-item draggable' data-value='" + i + "' title='" + "My title" + "'> Button " + i + "</div>").draggable();

Upvotes: 3

Related Questions