Create a repeated section with jQuery

The script in this post, allows you to create a repeated section where “add” link adds a new section identical to the current one below, while the “remove” link will remove the current section.

function makeRepeater(sectionsSelector, addClass, removeClass, AYSMsg){
   (function($){
      $(
         sectionsSelector + " " + addClass +","+
         sectionsSelector + " " + removeClass
      ).on("click", function(event){
         // Avoiding the link to do the default behavior.
         event.preventDefault();

         // Get the container to be removed/cloned
         var theContainer = $(this).parents(sectionsSelector);
         if($(this).is(addClass)){

            // Cloning the container with events
            var clonedSection = $(theContainer).clone(true);

            // And appending it just after the current container
            $(clonedSection).insertAfter(theContainer);
         }else{
            // If the user confirm the "Are You Sure" message 
            // we can remove the current container
            if(confirm(AYSMsg)){

               // Making fade out, hide and remove element a sequence
               // to provide a nice UX when removing element. 
               $(theContainer).fadeOut('normal', 
                  function( ){
                     $(this).hide('fast', 
                        function(){ $(this).remove();  } 
                     );
                  } 
               );
            }
         }
      });
   })(jQuery);
}

This simple method can be used in a really simple way:

makeRepeater(
    '.my-repeated-section',   /* The container selector */
    '.add',                   /* The add action selector */
    '.remove',                /* The remove action selector */
    'Are you sure you want to remove this section?' /* The AYS message. */
);

This would be the HTML:

<div class="group-of-repeated-sections">
    <div class="my-repeated-section">
        <input type="text" value="My repeated section" />
        <span>
            <a href="#" class="add"> + </a>
            <a href="#" class="remove"> - </a> 
        </span>
    </div>
</div>

Update: I’have prepared a live example on jsFiddle