1

I have made on click function for dynamic elements but its not working, Is there a way around it?

$( "p" ).on( "myCustomEvent", function( event, myName ) {

  $( this ).text( myName + ", hi there!" );

  $( "span" )
    .stop()
    .css( "opacity", 1 )
    .text( "myName = " + myName )
    .fadeIn( 30 )
    .fadeOut( 5000 );
});

$( "button" ).click(function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
  //alert(1);
});

var loop = setInterval(function(){
    $('.box').append('<button>Trigger custom event</button>');

},1000);

window.setTimeout(function(){ clearInterval(loop); },2000);

For code click here

Nishit Maheta
  • 5,916
  • 3
  • 14
  • 31
Rupesh
  • 137
  • 1
  • 9

1 Answers1

1

use below code

you need to learn about event-delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

DEMO

 $( document ).on('click',"button",function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
 });

NOTE : you can use nearest static parent selector instead of document.

Nishit Maheta
  • 5,916
  • 3
  • 14
  • 31