0
$(document).ready(function(){
    var t = $("<div><button class='leaf' id='l2'>Awesome!</button></div>");
   $('#l1').click(function(){
       $('#num').text("four");
       }); 
    $('.oright').click(function(){
       $('#num').text("Five");
       $('.oright').after(t);
       $('.oright').remove();
    });
    $('#l2').on('click', function(){
       $('#num').text("Reset?");
    });
});

The #l2 button doesn't have any functionality. I don't see any Syntax error, I looked it up and read that .on('click') was better than .click for dynamic elements, so I changed that but it still doesn't work.

null
  • 35
  • 7

2 Answers2

1

You'll have to delegate to make that work

$(document).on('click', '#l2', function(){
   $('#num').text("Reset?");
});

preferably you'd replace document with the closest non-dynamic parent element

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • For the OP, more written on the delegated form of `.on()` [here](http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht/8752376#8752376) and [here](http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre/9814409#9814409). – jfriend00 Apr 27 '14 at 20:43
  • Thank you both. It still isn't working but I know now the path to figure out why. – null Apr 27 '14 at 20:55
0

Because you have defined the new button markup as a jquery object - t - you can assign the click handler to it.

$(document).ready(function(){
    var t = $("<div><button class='leaf' id='l2'>Awesome!</button></div>");
   $('#l1').click(function(){
       $('#num').text("four");
       }); 
    $('.oright').click(function(){
       $('#num').text("Five");
       $('.oright').after(t);
       $('.oright').remove();
    });

    /* use the t jquery object you have defined */
    t.on('click', function(){
       $('#num').text("Reset?");
    });
});

Or delegate as @adeneo shows well

Rob Sedgwick
  • 5,216
  • 4
  • 20
  • 36