Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save/restore an object's location in the DOM tree?

Tags:

jquery

dom

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?

like image 535
Dane O'Connor Avatar asked Oct 19 '25 10:10

Dane O'Connor


1 Answers

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);
    }
}
like image 179
jfriend00 Avatar answered Oct 22 '25 00:10

jfriend00