TAGS :Viewed: 6 - Published at: a few seconds ago

[ jQuery Appended boxes not draggable ]

I have a jQuery UI code that allows an existing box to be draggable. When I append an additional box, however, those boxes are not draggable. Here's a JSFiddle: http://jsfiddle.net/MJKhq/4/ (the click me button adds another box to the document, but that box is not draggable like the first). Here's also a code sample because it required me to:

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

function makenew()
{
    $("body").append('<div id="draggable" class="ui-widget-content"> <p>Drag me around</p></div>');
}

Answer 1


Every dom element must have unique id to work on or parent must have to be different. You can not use same id, more after appending it to dom bind event on it. You can define it like this.

<script>
function _bindEvents()
{
    $(".ui-widget-content" ).draggable();
}

$(function(){
    _bindEvents();
});

function makenew()
{
    $("body").append('<div id="draggable" class="ui-widget-content"> <p>Drag me around</p></div>');
    _bindEvents();
}
</script>

Answer 2


There should be only one element with the same id in DOM tree. By adding a new box you get two elements with same id. Try using classes.

Answer 3


Remember id must be unique, you can't use same id more than one element on the same page and in this case you can use class instead of id, like

function makenew() {
    var div=$('<div class="draggable ui-widget-content"><p>Drag me around</p></div>');  
    $("body").append(div);
    $(div).draggable();
}

Example.