erikkallen
erikkallen

Reputation: 34421

JQuery preserve draggability when element is removed

I'm trying to move a draggable element around in the DOM, but whenever I try replaceWith() or remove() or similar functions, its draggability is lost.

Is it possible to make an element not lose its draggability when moving it around in the DOM?

Upvotes: 1

Views: 262

Answers (3)

erikkallen
erikkallen

Reputation: 34421

The solution is to not use jQuery to move the elements around, but to use the pure DOM.

That is, instead of

$('#elem').remove().appendTo($('#elem2'))

do

var q = $('#elem'); var el = q.get(0); el.parentNode.removeChild(el); $('#elem2').appendChild(el);

I don't know if it's recommended, but it works.

Upvotes: 2

razzed
razzed

Reputation: 2693

No, it's not possible to preserve draggability when you replace/remove elements in the DOM, unless you modify the jquery core (which I do not recommend.)

Doing replaceWith() and remove() for DOM elements means they are destroyed, and thus any behaviors or events associated with them are destroyed as well.

Try creating an outer <div> which contains the draggable behavior and instead replace the HTML within the div when you want to change the draggable item upon drop, etc.

Alternatively (and less elegant) you can call draggable() again on your elements after your do replaceWith() to restore the behavior you removed with replaceWith().

Likewise, instead of remove() try hide() to simply make elements disappear for a while but retain their behavior.

In short: You are approaching the problem incorrectly. Change your approach.

Upvotes: 0

TheVillageIdiot
TheVillageIdiot

Reputation: 40527

why don't you try to create the draggable behaviour again after you move around the DOM:

function xyz(){
    //move your stuff
    //create the draggable again

    $(element).draggable();
}

Upvotes: 0

Related Questions