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="p开发者_StackOverflowuzzlePiece_left_2" class="personal draggable ui-draggable">....</div>
Why would it not drag?
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.
Assuming you have a jquery selector that can find all of the elements you wish to make draggable, when you wish to make some newly added elements draggable, you could use the same selector in a new expression that just selects those that do not have ui-draggable class.
$(".selector:not(.ui-draggable)").draggable(draggableOptions);
精彩评论