If I have the following html:
<ul>
<li>test</li>
<li class='draggable'>special</li>
<li>test</li>
</ul>
How do I save .draggable
's current DOM location (generically)?
I plan on dragging this .draggable
around by by appending it to document.body
and making the position: absolute;
but I'll need to restore it if the user fails to do anything with it.
I could do this with clones, hiding the original, and using a proxy for dragging, but I feel like this problem has probably been solved more directly.
Thoughts?
To save an object's position, you can just save the DOM reference to the sibling before it. If there is no sibling before it, then save the parent.
function saveLocation(element) {
var loc = {};
var item = $(element).prev();
loc.element = element;
if (item.length) {
loc.prev = item[0];
} else {
loc.parent = $(element).parent()[0];
}
return(loc);
}
Then, to restore:
function restoreLocation(loc) {
if (loc.parent) {
$(loc.parent).prepend(loc.element);
} else {
$(loc.prev).after(loc.element);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With