A Web Design Community curated by Chris Coyier

Code Snippets Gallery

Code Snippets > jQuery > jQuery Duplicate Plugin Submit one!

jQuery Duplicate Plugin

$.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 Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.