Tuesday, November 22, 2016

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).

No comments:

Post a Comment

How to Put Google Adsense Below Post Title in Blogger?

Adsense is used by  majority  of expert bloggers for their website monetization because it is a cookie based contextual advertising syste...