4

so i am dynamically rendering a paragraph with jquery using the append method and i want to add a click event to it but for some reason the click event is not working, i know the solution is probably simple but I am new to jquery and would appreciate any help...I know the code inside the function works because i tested it with a static button, it is just not working with the dynamic one..Thanks in advance for any help,

here is my code

$(this).parent().parent().children("div").append("<p class='tryAgain'>Try Again</p>");

the click function code,

$(".tryAgain").click(function() {......}
skevthedev
  • 447
  • 1
  • 7
  • 20
  • welcome to jquery. If you like more information on clicks, [click this link to similar question here](http://stackoverflow.com/questions/2954932/difference-between-jquery-click-bind-live-delegate-and-trigger-functions-wit). And please note that with latest jquery version (1.7), all event binding methods have been fused into one method to rule them all: `.on()` – roselan Nov 15 '11 at 19:55

5 Answers5

7

Anything you add to the DOM after the document.ready has fired needs to use .live or .delegate in order to add an event handler to the newly added element.

For instance:

$('.tryAgain').live("click", function() {...});

If you are using jquery 1.7+ you should use .on:

$(document).on("click", ".tryAgain", function(){ ... });
amurra
  • 15,221
  • 4
  • 70
  • 87
1

Try with $.live o $.delegate.

Galled
  • 4,146
  • 2
  • 28
  • 41
1

Use:

$('.tryAgain').live('click', function()
{
  ....
});
Tessmore
  • 1,054
  • 1
  • 9
  • 23
0

There is an alternative to use live events, you can add the handler when you create the element like this:

$("<p>Try Again</p>", {
  "class": "tryAgain",
  click: function(){
     //YOUR CLICK HANDLER
  }
}).appendTo($(this).parent().parent().children("div"));
topek
  • 18,609
  • 3
  • 35
  • 43
0

I think you can attach a click event right there when you create the new p tag like this:

$(this).parent().parent().children("div").append(
    $('<p>').addClass('tryAgain').click(function(){
        alert('test');
    }));
arb
  • 7,753
  • 7
  • 31
  • 66