2

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

2
  • 1
    use jquery migrate library Commented Jul 30, 2015 at 9:26
  • 2
    $(document).on('click', 'p', handler); Commented Jul 30, 2015 at 9:27

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.