-1

I have a small code, that responsible for drawing newly added comments. THe problem is, when i rewrote code to use on instead of removed live, my code doesnt work on new elements, that were added after page load

Here is my code

$(function(){
    $('.show-comment-form').on("click", (function(){
        dataattr = $(this).data('comment');
        $('#new_comment').remove();
        $('.message-'+dataattr).append(partial_form);
        $("#comment_parent_id").val(dataattr);
        return false;
    }))
})

HTML

<a href="/phrases/52/create_comment?parent_id=16" class="show-comment-form" data-comment="16">Reply</a>

How do i add click event to all future elements, that will be added after page load?

Ian
  • 50,146
  • 13
  • 101
  • 111
sanny Sin
  • 1,555
  • 3
  • 17
  • 27

1 Answers1

7

Change:

$('.show-comment-form').on("click", (function(){

to:

$(document).on("click", '.show-comment-form', (function(){

When adding elements dynamically, to use on you target an element that exists on the page already, in this example document, then you pass the element you want to attach the listener to as a parameter to .on().

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

Also note that you want to target an element as close to the dynamically inserted elements as possible:

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    Using the `document` for the context isn't a smart move. – tomsseisums May 15 '13 at 13:45
  • 3
    @psycketom That's the best that can be used with this example - no other HTML is given. At the same time, I agree, and that should be included in the answer – Ian May 15 '13 at 13:45
  • 1
    @psycketom - As Ian said, `document` is a worst case example. It's always better to target an element closer to the actual element you will be binding to. – j08691 May 15 '13 at 13:46