Mile Mile - 1 year ago 83
HTML Question

How do you make prepended elements draggable

I have a code that adds elements upon the click of a button.



$(document).ready(function(){
$("#add_txt").click(function(){
$("body").prepend('<input class="style_txt">');
});
});


//However when I add...

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

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<button class="btn" id="add_txt">Add Text</button>





The element can not be dragged? Why is this?

Answer Source

you can't do it with input element, wrap it inside span

$(document).ready(function() {
  $("#add_txt").click(function() {
    $("body").prepend('<span><input class="style_txt"></span>');
    $(".style_txt").parent().draggable();
  });
});
span {
  padding: 5px;
  border: 1px solid #eee;
  cursor: move;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<button class="btn" id="add_txt">Add Text</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download