0

I am cloning a div and appending it to a parent div on different button click. this cloning and appending event is happening from different different JS files, so I want an event to be triggered when element is added to parent div. One method is to go and add the same code or call a function different places. I was wondering if there is an inbuilt function in jquery which will be triggered when any child is appended to it. Following is my code(Fiddle)

JS/Jquery:
$('.but').on('click',function(){    
    $('.sample').clone(true)
    .removeClass('sample')
    .addClass($(this).text())
    .appendTo($('.parent'));
    $('.rem').fadeIn();
});
$('.rem').on('click',function(){
    $('.parent').children('.com:last-child').remove();
});


  /*this is my conventional code this will be trigged every time when new element is added to parent div
   if(elements are increased in parent div){
      do your thing
   }
*/
HTML:
<div class="button-wrp">
    <div class="but cm">red</div>
    <div class="but cm">green</div>
    <div class="but cm">blue</div>
    <div class="rem cm">Remove</div>
</div>
<div class="parent"></div>
<div class="sample com"></div>

If you want to see all this thing working, please click on fiddle link

Bharat Soni
  • 2,824
  • 6
  • 23
  • 48
  • Possible duplicate of http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener/11546242#11546242 – UweB Mar 26 '14 at 14:24
  • You can look at http://stackoverflow.com/questions/7167085/on-append-do-something for a slightly different approach – Raphaël Althaus Mar 26 '14 at 14:25
  • This http://stackoverflow.com/a/16265881/592253 demonstrates the deprecated mutation events and the newer mutation observer. – Xotic750 Mar 26 '14 at 14:45

1 Answers1

0

You can use the jQuery event system. This would the idea:

First you set your listener:

$( 'div' ).on( 'child_appended', function(){
    // this is your parent with a new child
    var parent_with_new_child = this;
} );

And then when you append a new child you can to this:

$( '.parent' ).append( $( '.child' ) ).trigger( 'child_appended' );

For more reference go here

Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41