Search code examples
javascriptjqueryclick

click on jquery created element is not working


I create an element using Jquery and give it the class .book:

jQuery('<div/>', {
    name: "my name",
    class: 'book',
    text: 'Bookmark',
}).appendTo('body');

then i want to do something when that class is clicked, so naturally I wrote a quick and easy:

$('.book').click(function(){
    alert('I have been clicked');
});

That works

what does not work, is if I have it add those elements on click. so the following does not work:

var bms = 0;
$('button').click(function(){
    bms += 1;
    jQuery('<div/>', {
        name: bms,
        class: 'book',
        text: 'Bookmark ' + bms
    }).appendTo('body');
});
$('.book').click(function(){
    alert('I have been clicked');
});

why does this happen, and how can I fix this?

Jsfiddle

another thing:

Also, if I already have a div with the class .book in my body, the click event will work on that one, but not any of the appended divs. here is another jsfiddle to show that


Solution

  • You have to delegate to the newly created elements, like so...

    Just replace this...

    $('.book').click(function(){
      alert('I have been clicked');
    });
    

    With this....

    $(document).on('click','.book', function(){
      alert('I have been clicked');
    });