Tutorial jQuery Duplicate Plugin

by in , 0

$.fn.duplicate = function(count, cloneEvents) {
       var tmp = [];
       for ( var i = 0; i < count; i++ ) {
               $.merge( tmp, this.clone( cloneEvents ).get() );
       }
       return this.pushStack( tmp );
};

The .clone() function of jQuery will duplicate a set once, but what if you need multiple copies of the same set? You would have to do:

$(elem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem);

Now you can just:

$(elem)
   .duplicate(n)
   .appendTo(otherElem);

The first parameter is the number of clones you want and the second optional parameter is a boolean which controls if you want the events bound to those existing elements to be attached to the clones as well (or not).

Reference URL

Leave a Reply