views:

22

answers:

1

I am adding a draggable DIV dynamically but when I click and hold on it to drag it, it will not drag. I am adding it like so:

$("#leftPersonalContent").append(leftSlotContent);
$("#" + firstID).addClass("ui-draggable");

where leftSlotContent is of the form <div id="puzzlePiece_left_2" class="personal draggable ui-draggable">....</div> and firstID is "puzzlePiece_left_2".

After the element has been added I used Inspect Element (in Chrome) to see the actual code generated and it looks like this:

<div id="puzzlePiece_left_2" class="personal draggable ui-draggable">....</div>

Why would it not drag?

+1  A: 

Most likely because the element did not exist when you executed the code to setup the dragging. You need to register that with a live() listener.

EDIT

Since we're not dealing with events, I guess live() is not an option. I'll get to the solution shortly, but first let me explain what's going on with your current code, and why that's not working.

The snippet you posted in a comment here starts off with finding a set of elements - $('.draggable') - upon which you subsequently call .draggable() to make them draggable. All the elements that are returned by that first selector, will be made draggable. This is not a "rule" of any kind, that is stored away and continuously inspected, but just a simple one-time retrieval of items onto which to apply a function.

At the time when this code is executed, the selector $('.draggable') does not return your DIV in its set of results, as it does not exist at that point. When it suddenly comes into existence, that still doesn't change the fact that it was not one of the items that were once returned by $('.draggable') when the draggable was initiated. It would be returned, however, had that query been executed now, so that's exactly what we'll need to do - execute that same query once more.

So whenever you add a new item to be made draggable, you need to first destroy your current draggable:

$('.draggable').draggable('destroy');

... and then create it once more, now that the new item is in the set:

$('.draggable').draggable( { your options... } );

That ought to do it.

David Hedlund
Can you expand on that a little? I have a function that handles the dragging that looks like this: $('.draggable').draggable( { revert: 'invalid', scroll: false, zIndex: 1, helper: function (event) { var ret = $(this).clone(); ret.css("margin-left",$(this).css("margin-left")); return ret; }, start: function (event, ui) { ..... Are you saying I need to bind that function to the newly added draggable DIV?
Luke
@Luke: alright, see my edit
David Hedlund