views:

91

answers:

4

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?

A: 

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();
}
TheVillageIdiot
Because due to how my architecture is, I can't
erikkallen
A: 

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.

razzed
+1  A: 

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.

erikkallen
A: 

Thanks erikkallen! this solved my problem where i am using jQuery to move container div elements that have internal elements applied with non-jQuery events too. jQuery's .detach() method doesnt solve this problem, because the events referenced are not jQuery events so they get killed during the .append() method.

Dom A