JQuery - move an element and return to its previous location?

I am trying to use jQuery to move an element from one place to another in the DOM. Are there elements identical to the original container next to it, so how can I keep its exact previous location so that it returns to it? Here is an example ...

<div class="container"></div>
<ul>
    <li></li>
    <li><div class="move">Content</div></li>
    <li></li>
    <li><div class="move">Content</div></li>
    <li></li>
</ul>

... divs "move" individually move to the div "container", and then return to their previous location in the event via jQuery.appendTo (). How can I ensure that each "move" div returns to its exact previous location, determining where it was moved from (its exact location in the DOM relative to the document or otherwise specified parent container)?

EDIT: I fixed the classes in a div, since the specific case I'm working with has list items that are exact duplicates of each other (structurally), with unique content within their respective elements. In addition, the event to move the “move” div back to its original location is a button pressed inside it. How does a roaming item know where to go back to a roaming one (in particular, how does it know which list item is in the list)?

+5
source share
3 answers

you can clonethem, appendthem and, finally, the hideoriginal div, and at the end the removecloned div and the showoriginal.

+3
source

. , , .

, div.move, div container.

CSS

.placeholder { display:none; }

JS:

var id,
    gid = 0;

$('.move').click(function(e){
    if(!$(this).parents('.container')){
        // Move to container
        id = 'placeholder-' + gid++;
        $(this)
            .before('<div class="placeholder ' + id + '"></div>')  // Save a DOM "bookmark"
            .appendTo('.container')                               // Move the element to container
            .data('placeholder', id);                              // Store it placeholder info
    }
    else{
        // Move back out of container
        $(this)
            .appendTo('.placeholder.' + $(this).data('placeholder'))  // Move it back to it proper location
            .unwrap()                               // Remove the placeholder
            .data('placeholder', undefined);        // Unset placeholder data
     }
 });

HTML- div.move:

<div class="container">
    <div class="move>Content</div>
</div>
<ul>
    <li></li>
    <li><div class="placeholder placeholder-0"></div></li>
    <li></li>
    <li><div class="move">Content</div></li>
    <li></li>
</ul>

, . , . :

  • (, )
  • DOM
  • , .

? . . YMMV.

+2

.parent() , .append() .appendTo(), .

+1

All Articles