Why Insertbefore, On This Scenario, Delete My Element?
Solution 1:
If you just want to swap items 2 and 3, you may do this :
$('#try3').insertBefore($('#try2'));
There is no reason here to be more complex. If you'd wanted to swap items 1 and 3, you could do
$('#try3').insertBefore($('#try1'));
$('#try1').insertAfter($('#try2'));
You just put the item where you want it to be.
EDIT :
I made this function which swaps 2 elements that are childs of the same element (we could generalize but this would need more tests : last child, only child, etc.) :
functionswap($a, $b) { // a and b are (different) $jquery elementsif ($b.index()<$a.index()) {
var t = $a;
$a = $b; $b = t;
}
if ($b.index()==$a.index()+1) {
$b.insertBefore($a);
} else {
var$c = $a.next();
$a.insertBefore($b);
$b.insertBefore($c);
}
}
It can be tested here : http://jsfiddle.net/ferJR/
Solution 2:
ImmagineDrop.insertBefore($('.try').eq(swap1));
At this time, $('.try').eq(swap1)
is ImmagineDrop
itself.
So it is same with ImmagineDrop.insertBefore(ImmagineDrop);
.
When you insert an element before the element itself, it will cause it be detached from the document.
Solution 3:
Here is the why :
var ImmagineDrag=$('#try3');
var ImmagineDrop=$('#try2');
var swap1 = ImmagineDrag.index();
var swap2 = ImmagineDrop.index();
//at this point:
// swap1 contains the value: 2
// swap2 contains the value: 1
// $('.try').eq(swap2) selects $('#try2')
ImmagineDrag.insertBefore($('.try').eq(swap2));
// now $('#try3') has been inserted before '#try2'
// the order is now: try1, try3, try2
// the order of the nodes have changed :
// swap1 is still 2,
// so $('.try').eq(swap1) selects the third element
// which is now '#try2'
// this action tries to insert '#try2' before itself !
ImmagineDrop.insertBefore($('.try').eq(swap1));
// hence your problem...
As to how to fix it : you could use a placeholder
function swap(node1, node2){ //2 nodes
$placeHolder = $('<span>').insertBefore(node1);
$(node1).insertBefore(node2);
$(node2).insertBefore($placeHolder);
$placeHolder.remove();
}
but be aware that such a function does not work correctly if node1 == node2, or if node1 is a descendant of node2.
Post a Comment for "Why Insertbefore, On This Scenario, Delete My Element?"