answer99
answer99

Reputation: 251

Need click to trigger after appending element

Please see the below code:

HTML:

<p>Click this paragraph.</p>

JS:

$("p").live("click", function(){
    alert("The paragraph was clicked.");  

    $("body").append("<p>This was newly added. this has also click</p>")
});

Now the element is appending correctly. But the click is not triggering for the appended element. If i am using live instead of on its working fine. But live was depreciated. What to do.

JSfiddle

Upvotes: 2

Views: 185

Answers (2)

fuyushimoya
fuyushimoya

Reputation: 9813

Use the delegate style for .on

.on( events [, selector ] [, data ], handler )

  • events Type: String One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
  • selector Type: String A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
  • data Type: Anything Data to be passed to the handler in event.data when an event is triggered.
  • handler Type: Function( Event eventObject [, Anything extraParameter ] [, ... ] ) A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.

As you don't want to pass data, you can write in form:

$(body).on('click', 'p', handler)

which omits the data param.

$("body").on("click", "p", function(){
    alert("The paragraph was clicked.");  

    $("body").append("<p>This was newly added. this has also click</p>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Click this paragraph.</p>

Upvotes: 3

Albzi
Albzi

Reputation: 15609

Change it to this:

$("body").on("click", "p", function(){
    alert("The paragraph was clicked.");  

    $("body").append("<p>This was newly added. this has also click</p>")
});

JSFiddle

You don't want to use p as that will only work on the p elements that are already on the page, so new ones that you append wont work.

If you use the body and set it so when you click on a p, do the function, it will work.

Upvotes: 3

Related Questions