Search code examples
jqueryappendcloneparentprepend

Parent/Append/Prepend arrangement


On a doubleclick, a new clone of the clicked element is created. It's imperative that this new clone is prepended to the parent wrapper. However, this becomes problematic as there is an element above the clone targets. The clones that are produced are placed above this misc element. I need to have the clones placed above the original, but below this misc element.

<div id="wrapper">

----> <img class="clone_target Copy"/> *prepend places them here.

<span class="misc_element"></span>

----> <img class="clone_target Copy"/> *the clones should go here.

<img class="clone_target"/>

</div>

Solution

  • You can do

    $('.clone_target').dblclick(function (e) {
        $(this).before($(this).clone().addClass('copy'));
    });
    

    To limit the number of copies made,

    var MAX_CLONES = 30;
    $('.clone_target').dblclick(function (e) {
        if ($(this).prevUntil('.misc_element').length < MAX_CLONES) {
            $(this).before($(this).clone().addClass('copy'));
        }
    });