I have detached a div and want to re-attach it when clicking on a button.
Here\'s the code:
$(\'#wrapper\').detach();
$(\"#open_menu\").click(functi
I think this is largely a matter of recording the index of the element that will be detached, before detaching it, then using that index for determining where to re-attach the element. Consider the following "repl" https://repl.it/@dexygen/re-attach and the code below. The setTimeout
is merely so you can see the element in the page before it gets detached, and a couple of elements have been renamed. I wonder if siblings
can be used instead of parent().children()
but am concerned what happens in the event the detached sibling is the only element among siblings, and we need a reference to parent
anyway, for prepending if index === 0
.
setTimeout(function() {
var bar = $('#bar');
var parent = bar.parent();
var index = parent.children().index(bar);
bar.detach();
$("#re-attach").one('click', function() {
if (index === 0) {
parent.prepend(bar);
}
else {
parent.children().eq(index-1).after(bar);
}
});
}, 5000);