Question

When I add a comment, and hit the click-able text "Edit" the alert box doesn't pop up. First when I add the second comment, I'm able to hit the "edit" on the first one comment, and the alert box pop up.

Image

Why that??

Live Demo

function addComment(name1) {

    var container = $('#divComments');
    var inputs = container.find('label');
    var id = inputs.length + 1;

    var div = $('<div />', {
        class: 'CommentStyle'
    });

    $('<label />', {
        id: 'comment' + id,
        text: name1
    }).appendTo(div);

    var d = new Date();
    var $fulaDate = $('<div class="floatleft">' + d.getFullYear() + "-" + monthNames[d.getMonth()] + "-" + d.getDate() + "T" + d.getHours() + ":" + d.getMinutes() + '</div>').appendTo(div);

    var $edit = $('<p />', { class: 'edit', text: 'Edit' }).addClass('edit').appendTo(div);

    $('.edit').click(function () {
        alert('Hallo');

    });

    div.appendTo(container);

}
Was it helpful?

Solution

You need to use event delegation for dynamically created elements:

$('#divComments').on('click','.edit',function () {
    alert('Hallo');
});

Also, as suggested by @Archer, you need to move the click handler outside of your function to avoid nested click events from firing multiple times.

Updated Fiddle

OTHER TIPS

Problem with your implementation is that when you are attaching event like

var $edit = $('<p />', { class: 'edit', text: 'Edit' }).addClass('edit').appendTo(div);
$('.edit').click(function () {
    alert('Hallo');
});

Edit element which you created just now is not added to DOM it is appeded to div only, which is not added to DOM. thus in short it doesn't exists in DOM, thus event is not binded with the button.

So to fix the issue instead of binding event to $('.edit') you need to bind event with $edit.

var $edit = $('<p />', { class: 'edit', text: 'Edit' }).appendTo(div);
$edit.click(function () {
    alert('Hallo');
});

DEMO

However I would recommend you to use Event Delegation as

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Code

function addComment(name1) {
}
$('#divComments').on('click', '.edit', function () {
    alert('Hallo');
});

DEMO with event delegation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top