This is my code taken from http://jqueryui.com/demos/draggable/
try calling $( ".draggable" ).draggable();
once the dynamically created element is added.
$(function() {
$( ".draggable" ).draggable();
$('.content').click(function(){
var htmlData='<div class="draggable ui-widget-content ui-draggable"><p>Drag me around</p></div>';
$('.demo').append(htmlData);
$( ".draggable" ).draggable();
});
});
Working Demo
<script>
$(function() {
$(".draggable").draggable();
$(".content").click(function(){
var htmlData='<div class="draggable ui-widget-content ui-draggable"><p>Drag me around</p></div>';
$(".demo").append(htmlData);
});
});
</script>
Just a need for position changing is needed
<script>
$(function() {
$(".content").click(function(){
var htmlData='<div class="draggable ui-widget-content ui-draggable"><p>Drag me around</p></div>';
$(".demo").append(htmlData);
$(".draggable").draggable(); //bring it here so that for the newly inserted/created dom elements, jquery draggable can be initialized.
});
});
</script>
I would recommend doing it like this because if you want to pass a configuration object to the draggable function, you won't have to repeat it in two different places:
<script>
$(function() {
setDraggable();
$('.content').click(function(){
var htmlData='<div class="draggable ui-widget-content ui-draggable"><p>Drag me around</p></div>';
$('.demo').append(htmlData);
setDraggable();
});
});
function setDraggable(){
$( ".draggable" ).draggable();
}
</script>
I'm actually going to say for performance reasons, to instead use:
$('.draggable:not(.ui-draggable)').draggable();
This will prevent attempting to re-initialize already draggable elements using jQuery UI's built in class. Also, if your code down the road modifies the properties of an individual draggable that may not match the properties of a new draggable, you could end up with some being reset.
Nothing wrong with being specific with jQuery.
UPDATE
Didn't specify for which instance to use this. Based on Ricardo's Edit:
$(function() {
$( ".draggable" ).draggable();
$('.content').click(function(){
var htmlData='<div class="draggable ui-widget-content"><p>Drag me around</p></div>';
$('.demo').append(htmlData);
$('.draggable:not(.ui-draggable)').draggable(); //Here
});
});
I'm also now seeing you were manually adding the ui-draggable class. You don't need to do that. In fact, it makes what I said not work.